Skip to main content

native_theme/
fonts.rs

1//! Font matching, and the platform's own typeface for a family.
2//!
3//! [`select_face`] is the one matcher — CSS Fonts Module Level 4 §5.1
4//! "Localized name matching" and §5.2 "Matching font styles" over a list of
5//! face descriptions — and needs no font database, so it is compiled
6//! unconditionally. Behind the `system-fonts` feature, `system_face` runs
7//! it over the system font database, loaded once per process, and returns
8//! the chosen face's bytes; on macOS the system UI font is found by its file
9//! through Core Text, because no font database files it under the name the
10//! platform documents. `system_face` substitutes no family; `substitute_family`,
11//! behind the same feature, names the family the platform draws in place of
12//! one it has no face of — on Linux and the other fontconfig platforms,
13//! fontconfig's best match, which `system_face` then finds by name.
14
15use crate::theme::FontStyle;
16
17/// What [`select_face`] knows about one candidate face.
18#[derive(Clone, Copy, Debug)]
19pub struct FaceTraits<'a> {
20    /// Every family name the face records.
21    pub families: &'a [&'a str],
22    /// OS/2 `usWidthClass`, `1..=9`; `5` is normal.
23    pub width: u16,
24    /// The face's style.
25    pub style: FontStyle,
26    /// OS/2 `usWeightClass`, the CSS weight.
27    pub weight: u16,
28}
29
30/// The index in `faces` of the face CSS Fonts Module Level 4 selects for
31/// `family`, `weight` and `style`, or `None` where no face records `family`.
32///
33/// Only faces one of whose family names equals `family` under Unicode
34/// default caseless matching (§5.1 "Localized name matching"; `unicase`)
35/// are candidates, and **no other family is ever substituted**: an empty
36/// candidate set is `None`. Among the candidates the three steps of §5.2
37/// "Matching font styles" narrow the set in order, with the model's
38/// normal width — `font-width`: normal first, then narrower widths
39/// descending, then wider ascending; `font-style`: `Italic` takes italic,
40/// then oblique, then normal, `Oblique` oblique, italic, normal, and
41/// `Normal` normal, oblique, italic; `font-weight`: for a desired weight
42/// inclusively between 400 and 500, weights at or above it ascending up to
43/// and including 500, then below it descending, then above 500; below 400,
44/// weights at or below it descending, then above it ascending; above 500,
45/// weights at or above it ascending, then below it descending — and the
46/// first face in `faces` order among those left is returned.
47///
48/// fontdb's own `query` is deliberately not used: it compares family names
49/// case-sensitively, and its weight step follows Level 3 with a `450`
50/// cut-off, which picks `300` where Level 4 picks `450` for a desired `400`.
51#[must_use]
52pub fn select_face(
53    faces: &[FaceTraits<'_>],
54    family: &str,
55    weight: u16,
56    style: FontStyle,
57) -> Option<usize> {
58    let wanted = unicase::UniCase::new(family);
59    let mut candidates: Vec<(usize, &FaceTraits<'_>)> = faces
60        .iter()
61        .enumerate()
62        .filter(|(_, face)| {
63            face.families
64                .iter()
65                .any(|name| unicase::UniCase::new(*name) == wanted)
66        })
67        .collect();
68    if candidates.is_empty() {
69        return None;
70    }
71    keep_best(&mut candidates, |face| width_rank(face.width));
72    keep_best(&mut candidates, |face| style_rank(face.style, style));
73    keep_best(&mut candidates, |face| weight_rank(face.weight, weight));
74    candidates.first().map(|(index, _)| *index)
75}
76
77/// Keep the candidates of the lowest rank.
78fn keep_best(
79    candidates: &mut Vec<(usize, &FaceTraits<'_>)>,
80    rank: impl Fn(&FaceTraits<'_>) -> (u8, u16),
81) {
82    if let Some(best) = candidates.iter().map(|(_, face)| rank(face)).min() {
83        candidates.retain(|(_, face)| rank(face) == best);
84    }
85}
86
87/// §5.2 `font-width` for the normal width: `(group, distance)`, lower first.
88fn width_rank(width: u16) -> (u8, u16) {
89    const NORMAL: u16 = 5;
90    match width.cmp(&NORMAL) {
91        std::cmp::Ordering::Equal => (0, 0),
92        std::cmp::Ordering::Less => (1, NORMAL.saturating_sub(width)),
93        std::cmp::Ordering::Greater => (2, width),
94    }
95}
96
97/// §5.2 `font-style`: the position of `face` in the order `wanted` sets.
98fn style_rank(face: FontStyle, wanted: FontStyle) -> (u8, u16) {
99    let rank = match (wanted, face) {
100        (w, f) if w == f => 0,
101        (FontStyle::Italic, FontStyle::Oblique)
102        | (FontStyle::Oblique, FontStyle::Italic)
103        | (FontStyle::Normal, FontStyle::Oblique) => 1,
104        _ => 2,
105    };
106    (rank, 0)
107}
108
109/// §5.2 `font-weight`: the three quoted rules as `(group, distance)`.
110fn weight_rank(face: u16, wanted: u16) -> (u8, u16) {
111    let below = wanted.saturating_sub(face);
112    match wanted {
113        400..=500 if face >= wanted && face <= 500 => (0, face),
114        400..=500 if face < wanted => (1, below),
115        400..=500 => (2, face),
116        0..=399 if face <= wanted => (0, below),
117        0..=399 => (1, face),
118        _ if face >= wanted => (0, face),
119        _ => (1, below),
120    }
121}
122
123/// Whether `family` names the macOS system UI font: caselessly equal to
124/// "SF Pro", the name the platform documents for it
125/// (`docs/platform-facts.md:63-71`) and `macos-monterey` states. A pure
126/// predicate, on every platform, with no font database: `system_face`'s
127/// macOS branch asks it beside its Core Text family comparison, and the
128/// gpui connector asks it alone to map the family to gpui's own alias.
129#[must_use]
130pub fn is_macos_system_ui_family(family: &str) -> bool {
131    unicase::UniCase::new(family) == unicase::UniCase::new("SF Pro")
132}
133
134/// Whether `family` names the macOS system monospaced font: caselessly equal
135/// to "SF Mono", the name the platform facts give
136/// `+monospacedSystemFontOfSize:weight:` (`docs/platform-facts.md:65`) and the
137/// macOS presets state. The font's family name is
138/// `.AppleSystemUIFontMonospaced`, as macOS 26 reports it
139/// (`docs/evidence/os-probe/2026-10-11-run-38129819806/os-probe-macos-26/probe.toml:162`);
140/// whether "SF Mono" is a family name a font database holds stays open
141/// there. A pure
142/// predicate, on every platform, with no font database: the gpui connector
143/// asks it to map the family to that face, as it maps
144/// [`is_macos_system_ui_family`]'s.
145#[must_use]
146pub fn is_macos_system_mono_family(family: &str) -> bool {
147    unicase::UniCase::new(family) == unicase::UniCase::new("SF Mono")
148}
149
150/// A face [`system_face`] chose: its bytes, and what fontdb records for it.
151#[cfg(feature = "system-fonts")]
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct SystemFace {
154    /// The face's file, whole: for a face of a collection (`.ttc`), the
155    /// collection, addressed by `index`.
156    pub data: std::sync::Arc<[u8]>,
157    /// The face's index in `data`.
158    pub index: u32,
159    /// The face's own family name as fontdb records it: the first of its
160    /// `FaceInfo::families`, "always English US, unless it's missing from
161    /// the font" (fontdb 0.23.0 `src/lib.rs` lines 826–827). A toolkit that draws
162    /// by name draws this one.
163    pub family: std::sync::Arc<str>,
164    /// The face's own weight, OS/2 `usWeightClass`.
165    pub weight: u16,
166    /// The face's own style.
167    pub style: FontStyle,
168}
169
170/// The system font database, loaded once per process and shared by every
171/// [`system_face`] call. A font installed while the process runs is seen
172/// after a restart, as with iced's own font system.
173#[cfg(feature = "system-fonts")]
174fn database() -> &'static fontdb::Database {
175    static DB: std::sync::OnceLock<fontdb::Database> = std::sync::OnceLock::new();
176    DB.get_or_init(|| {
177        let mut db = fontdb::Database::new();
178        db.load_system_fonts();
179        db
180    })
181}
182
183#[cfg(feature = "system-fonts")]
184fn style_of(style: fontdb::Style) -> FontStyle {
185    match style {
186        fontdb::Style::Normal => FontStyle::Normal,
187        fontdb::Style::Italic => FontStyle::Italic,
188        fontdb::Style::Oblique => FontStyle::Oblique,
189    }
190}
191
192/// [`select_face`] over `db`'s faces; the chosen face's bytes copied once.
193#[cfg(feature = "system-fonts")]
194fn face_in(
195    db: &fontdb::Database,
196    family: &str,
197    weight: u16,
198    style: FontStyle,
199) -> Option<SystemFace> {
200    let infos: Vec<&fontdb::FaceInfo> = db.faces().collect();
201    let names: Vec<Vec<&str>> = infos
202        .iter()
203        .map(|info| {
204            info.families
205                .iter()
206                .map(|(name, _)| name.as_str())
207                .collect()
208        })
209        .collect();
210    let traits: Vec<FaceTraits<'_>> = infos
211        .iter()
212        .zip(&names)
213        .map(|(info, names)| FaceTraits {
214            families: names,
215            width: info.stretch.to_number(),
216            style: style_of(info.style),
217            weight: info.weight.0,
218        })
219        .collect();
220    let chosen = select_face(&traits, family, weight, style)?;
221    let info = infos.get(chosen)?;
222    let (data, index) = db.with_face_data(info.id, |data, index| {
223        (std::sync::Arc::<[u8]>::from(data), index)
224    })?;
225    let (recorded, _) = info.families.first()?;
226    Some(SystemFace {
227        data,
228        index,
229        family: std::sync::Arc::from(recorded.as_str()),
230        weight: info.weight.0,
231        style: style_of(info.style),
232    })
233}
234
235/// The system's own face for `family`, `weight` and `style`, or `None`.
236///
237/// The first call in a process loads the system font database
238/// (`fontdb::Database::load_system_fonts`), which every later call shares;
239/// each call runs [`select_face`] over its faces and copies the chosen
240/// face's file into the returned [`SystemFace`], so call it when a theme
241/// changes, not per frame. A family the system has no face of is `None`:
242/// nothing is substituted here; [`substitute_family`] names the family the
243/// platform draws in its place, to ask this function for next. On macOS a
244/// `family` that names the system UI
245/// font — [`is_macos_system_ui_family`], or caselessly Core Text's own
246/// family name for it — is found by its file instead: fontdb files that
247/// font under `.SF NS`, not under the platform's name, so Core Text is
248/// asked which file its system font is (upright, or its italic for an
249/// `Italic` or `Oblique` style), that file alone is loaded, and
250/// [`select_face`] picks among its faces by width, style and weight under
251/// the family the file itself records; a `None` from Core Text, or a file
252/// that yields no face, is `None` here too. Every other family, on macOS as
253/// elsewhere, goes through the name lookup.
254#[cfg(feature = "system-fonts")]
255#[must_use]
256pub fn system_face(family: &str, weight: u16, style: FontStyle) -> Option<SystemFace> {
257    #[cfg(target_os = "macos")]
258    {
259        let italic = matches!(style, FontStyle::Italic | FontStyle::Oblique);
260        let ui = crate::macos::system_ui_font(italic);
261        let names_it = is_macos_system_ui_family(family)
262            || ui.as_ref().is_some_and(|font| {
263                unicase::UniCase::new(family) == unicase::UniCase::new(font.family.as_str())
264            });
265        if names_it {
266            return ui.and_then(|font| face_in_file(&font.path, weight, style));
267        }
268    }
269    face_in(database(), family, weight, style)
270}
271
272/// The face of one font file — the macOS system UI font's — selected by
273/// width, style and weight under the family the file's first face records.
274#[cfg(all(feature = "system-fonts", target_os = "macos"))]
275fn face_in_file(path: &std::path::Path, weight: u16, style: FontStyle) -> Option<SystemFace> {
276    let mut db = fontdb::Database::new();
277    db.load_font_file(path).ok()?;
278    let recorded = db.faces().next()?.families.first()?.0.clone();
279    face_in(&db, &recorded, weight, style)
280}
281
282/// The family the platform draws in place of `family`, or `None` where the
283/// platform has that family, gives no answer, or its fallback is not
284/// implemented here.
285///
286/// On Linux and the other fontconfig platforms — Unix other than macOS, iOS
287/// and Android — fontconfig is asked through its own `fc-match` tool, run as
288/// `fc-match --format=%{family[0]} <pattern>`: `fc-match` parses the pattern
289/// with `FcNameParse`, runs `FcConfigSubstitute` and `FcDefaultSubstitute`
290/// on it and prints `FcFontMatch`'s best match (fontconfig 2.15.0
291/// `fc-match/fc-match.c` lines 169, 188–189 and 218), which is the font
292/// every native application of the system gets for that family, and
293/// `%{family[0]}` is that match's first family name (`FcPatternFormat(3)`).
294/// The pattern is `family` with the characters fontconfig's name syntax
295/// reserves in a family — `\`, `-`, `:` and `,` — each preceded by a `\`
296/// (fontconfig user's guide, "Font Names"). `None` when `fc-match` cannot be
297/// run, fails, does not finish within 2 s, prints nothing, or prints a family
298/// caselessly equal to `family`: the system has that family, and
299/// [`system_face`] finds it by name. Each call starts a process, so call it
300/// when a theme changes, not per frame; [`substitute_family_cached`] asks
301/// once per family and keeps the answer for the process.
302///
303/// macOS, Windows and every other platform: `None`. Their own fallback for a
304/// missing family is not implemented: no code path of this crate reads it.
305#[cfg(feature = "system-fonts")]
306#[must_use]
307pub fn substitute_family(family: &str) -> Option<String> {
308    platform_substitute(family)
309}
310
311/// [`substitute_family`]'s answer for `family`, asked of the platform once
312/// per family and kept for the process, so a caller may ask every frame.
313///
314/// The first call for a family runs [`substitute_family`] on the calling
315/// thread: on Linux and the other fontconfig platforms one `fc-match`
316/// process, about 12.5 ms measured on one Linux machine, with a 2 s timeout.
317/// A thread asking for another family, or for one already answered, does not
318/// wait for it. Two first callers for one family may both ask; the answer is
319/// the same, and the last one is kept. A family installed after its first
320/// ask keeps the answer that ask gave for the rest of the process.
321#[cfg(feature = "system-fonts")]
322#[must_use]
323pub fn substitute_family_cached(family: &str) -> Option<String> {
324    static ASKED: std::sync::OnceLock<AskedFamilies> = std::sync::OnceLock::new();
325    asked_once(
326        ASKED.get_or_init(AskedFamilies::default),
327        family,
328        substitute_family,
329    )
330}
331
332/// Each family asked, with the platform's answer.
333#[cfg(feature = "system-fonts")]
334type AskedFamilies = std::sync::Mutex<std::collections::HashMap<String, Option<String>>>;
335
336/// `ask`'s answer for `family`, kept in `asked`. The lock is held for the
337/// look-up and the insert only, not across `ask`: the platform's ask starts
338/// a process ([`substitute_family`]: `fc-match` on Linux and the other
339/// fontconfig platforms, bounded by `SUBPROCESS_TIMEOUT`, 2 s,
340/// `src/detect.rs:20`), and a thread building any other theme must not wait
341/// for it. The 12.5 ms per ask the public docs state was measured by M6-03's
342/// verifier with a logging `fc-match` shim first on `PATH` over the gpui
343/// connector's release `timings` binary: two asks of about 12.5 ms in each
344/// preset's first call that brings two new families
345/// (docs/archive/todo_v0.7.0_code-review-findings.md, M6-03).
346#[cfg(feature = "system-fonts")]
347fn asked_once(
348    asked: &AskedFamilies,
349    family: &str,
350    ask: impl FnOnce(&str) -> Option<String>,
351) -> Option<String> {
352    let lock = || {
353        asked
354            .lock()
355            .unwrap_or_else(std::sync::PoisonError::into_inner)
356    };
357    let kept = lock().get(family).cloned();
358    if let Some(answer) = kept {
359        return answer;
360    }
361    let answer = ask(family);
362    lock().insert(family.to_owned(), answer.clone());
363    answer
364}
365
366#[cfg(all(
367    feature = "system-fonts",
368    unix,
369    not(target_os = "macos"),
370    not(target_os = "ios"),
371    not(target_os = "android")
372))]
373fn platform_substitute(family: &str) -> Option<String> {
374    let printed = crate::detect::stdout_with_timeout(
375        "fc-match",
376        &["--format=%{family[0]}", &fontconfig_family(family)],
377        crate::detect::SUBPROCESS_TIMEOUT,
378    )?;
379    let matched = printed.trim();
380    if matched.is_empty() || unicase::UniCase::new(matched) == unicase::UniCase::new(family) {
381        return None;
382    }
383    Some(matched.to_owned())
384}
385
386#[cfg(all(
387    feature = "system-fonts",
388    not(all(
389        unix,
390        not(target_os = "macos"),
391        not(target_os = "ios"),
392        not(target_os = "android")
393    ))
394))]
395fn platform_substitute(_family: &str) -> Option<String> {
396    None
397}
398
399/// `family` as a fontconfig pattern's family: "The '\\', '-', ':' and ','
400/// characters in family names must be preceded by a '\\' character to avoid
401/// having them misinterpreted" (fontconfig user's guide, "Font Names";
402/// `FcNameParse` reads the families up to an unescaped `-`, `,` or `:`, and
403/// takes the character after a `\` as it is, fontconfig 2.15.0
404/// `src/fcname.c` lines 415–443 and 467).
405#[cfg(all(
406    feature = "system-fonts",
407    unix,
408    not(target_os = "macos"),
409    not(target_os = "ios"),
410    not(target_os = "android")
411))]
412fn fontconfig_family(family: &str) -> String {
413    let mut pattern = String::with_capacity(family.len());
414    for c in family.chars() {
415        if matches!(c, '\\' | '-' | ':' | ',') {
416            pattern.push('\\');
417        }
418        pattern.push(c);
419    }
420    pattern
421}
422
423#[cfg(test)]
424#[allow(
425    clippy::unwrap_used,
426    clippy::expect_used,
427    clippy::panic,
428    clippy::indexing_slicing,
429    reason = "a test fails by panicking"
430)]
431mod tests {
432    use super::*;
433
434    const N: FontStyle = FontStyle::Normal;
435    const I: FontStyle = FontStyle::Italic;
436    const O: FontStyle = FontStyle::Oblique;
437
438    fn face(
439        families: &'static [&'static str],
440        width: u16,
441        style: FontStyle,
442        weight: u16,
443    ) -> FaceTraits<'static> {
444        FaceTraits {
445            families,
446            width,
447            style,
448            weight,
449        }
450    }
451
452    /// CSS Fonts Level 4 §5.1: names match case-insensitively by Unicode
453    /// default caseless matching; a family with no face is `None`, never
454    /// another family.
455    #[test]
456    fn the_family_is_matched_caselessly_and_never_substituted() {
457        let faces = [face(&["Inter"], 5, N, 400), face(&["Roboto"], 5, N, 400)];
458        assert_eq!(select_face(&faces, "inter", 400, N), Some(0));
459        assert_eq!(select_face(&faces, "INTER", 400, N), Some(0));
460        assert_eq!(select_face(&faces, "Helvetica", 400, N), None);
461        assert_eq!(select_face(&[], "Inter", 400, N), None);
462    }
463
464    /// Any of the names a face records matches, not only the first.
465    #[test]
466    fn any_recorded_family_name_matches() {
467        let faces = [face(&["Segoe UI", "Segoe UI Regular"], 5, N, 400)];
468        assert_eq!(select_face(&faces, "segoe ui regular", 400, N), Some(0));
469    }
470
471    /// §5.2 `font-width`, with the model's normal width `5`: normal first,
472    /// then narrower widths descending, then wider ascending.
473    #[test]
474    fn width_prefers_normal_then_narrower_descending_then_wider_ascending() {
475        let normal = [
476            face(&["F"], 3, N, 400),
477            face(&["F"], 7, N, 400),
478            face(&["F"], 5, N, 400),
479        ];
480        assert_eq!(select_face(&normal, "F", 400, N), Some(2));
481        let narrow = [
482            face(&["F"], 2, N, 400),
483            face(&["F"], 7, N, 400),
484            face(&["F"], 3, N, 400),
485        ];
486        assert_eq!(select_face(&narrow, "F", 400, N), Some(2));
487        let wide = [face(&["F"], 8, N, 400), face(&["F"], 6, N, 400)];
488        assert_eq!(select_face(&wide, "F", 400, N), Some(1));
489    }
490
491    /// §5.2 `font-style`: italic → italic, oblique, normal; oblique →
492    /// oblique, italic, normal; normal → normal, oblique, italic.
493    #[test]
494    fn style_falls_back_in_the_css_order() {
495        let no_italic = [face(&["F"], 5, N, 400), face(&["F"], 5, O, 400)];
496        assert_eq!(select_face(&no_italic, "F", 400, I), Some(1));
497        let no_oblique = [face(&["F"], 5, N, 400), face(&["F"], 5, I, 400)];
498        assert_eq!(select_face(&no_oblique, "F", 400, O), Some(1));
499        let no_normal = [face(&["F"], 5, I, 400), face(&["F"], 5, O, 400)];
500        assert_eq!(select_face(&no_normal, "F", 400, N), Some(1));
501        let exact = [face(&["F"], 5, O, 400), face(&["F"], 5, I, 400)];
502        assert_eq!(select_face(&exact, "F", 400, I), Some(1));
503    }
504
505    /// §5.2 `font-weight`, desired weight inclusively between 400 and 500:
506    /// weights at or above the target ascending up to and including 500,
507    /// then below descending, then above 500 ascending. Level 4 picks 450
508    /// for 400 from {300, 450}, where fontdb's Level 3 rule picks 300
509    /// (fontdb 0.23.0 `src/lib.rs` lines 1207–1208).
510    #[test]
511    fn weight_between_400_and_500_climbs_to_500_first() {
512        let faces = [face(&["F"], 5, N, 300), face(&["F"], 5, N, 450)];
513        assert_eq!(select_face(&faces, "F", 400, N), Some(1));
514        let faces = [face(&["F"], 5, N, 600), face(&["F"], 5, N, 300)];
515        assert_eq!(select_face(&faces, "F", 400, N), Some(1));
516        let faces = [face(&["F"], 5, N, 400), face(&["F"], 5, N, 500)];
517        assert_eq!(select_face(&faces, "F", 450, N), Some(1));
518        let faces = [face(&["F"], 5, N, 700), face(&["F"], 5, N, 400)];
519        assert_eq!(select_face(&faces, "F", 500, N), Some(1));
520    }
521
522    /// Desired weight below 400: at or below the target descending, then
523    /// above ascending.
524    #[test]
525    fn weight_below_400_descends_first() {
526        let faces = [face(&["F"], 5, N, 350), face(&["F"], 5, N, 200)];
527        assert_eq!(select_face(&faces, "F", 300, N), Some(1));
528        let faces = [face(&["F"], 5, N, 700), face(&["F"], 5, N, 350)];
529        assert_eq!(select_face(&faces, "F", 300, N), Some(1));
530    }
531
532    /// Desired weight above 500: at or above the target ascending, then
533    /// below descending.
534    #[test]
535    fn weight_above_500_ascends_first() {
536        let faces = [face(&["F"], 5, N, 600), face(&["F"], 5, N, 800)];
537        assert_eq!(select_face(&faces, "F", 700, N), Some(1));
538        let faces = [face(&["F"], 5, N, 500), face(&["F"], 5, N, 600)];
539        assert_eq!(select_face(&faces, "F", 700, N), Some(1));
540    }
541
542    /// The three steps narrow in order, and a tie keeps the first face.
543    #[test]
544    fn width_outranks_style_which_outranks_weight() {
545        let faces = [
546            face(&["F"], 3, N, 400),
547            face(&["F"], 5, I, 700),
548            face(&["F"], 5, I, 400),
549        ];
550        assert_eq!(select_face(&faces, "F", 400, N), Some(2));
551        let tie = [face(&["F"], 5, N, 400), face(&["F"], 5, N, 400)];
552        assert_eq!(select_face(&tie, "F", 400, N), Some(0));
553    }
554
555    /// The macOS system UI font's documented name, caselessly, and nothing
556    /// else (`docs/platform-facts.md:63-71`).
557    #[test]
558    fn the_macos_system_ui_family_is_sf_pro_caselessly() {
559        assert!(is_macos_system_ui_family("SF Pro"));
560        assert!(is_macos_system_ui_family("sf pro"));
561        assert!(!is_macos_system_ui_family("SF Mono"));
562        assert!(!is_macos_system_ui_family("SF Pro Text"));
563        assert!(!is_macos_system_ui_family("Inter"));
564    }
565
566    /// The macOS system monospaced font's stated name, caselessly, and
567    /// nothing else (`docs/platform-facts.md:65`).
568    #[test]
569    fn the_macos_system_mono_family_is_sf_mono_caselessly() {
570        assert!(is_macos_system_mono_family("SF Mono"));
571        assert!(is_macos_system_mono_family("sf mono"));
572        assert!(!is_macos_system_mono_family("SF Pro"));
573        assert!(!is_macos_system_mono_family("SF Mono Text"));
574        assert!(!is_macos_system_mono_family("Menlo"));
575    }
576
577    /// fontconfig's name-syntax specials in a family — `\`, `-`, `:` and `,` —
578    /// are each preceded by a `\`; every other character, a space included,
579    /// is kept as it is (fontconfig user's guide, "Font Names").
580    #[cfg(all(
581        feature = "system-fonts",
582        unix,
583        not(target_os = "macos"),
584        not(target_os = "ios"),
585        not(target_os = "android")
586    ))]
587    #[test]
588    fn a_fontconfig_family_escapes_the_name_syntax_specials() {
589        assert_eq!(fontconfig_family("JetBrains Mono"), "JetBrains Mono");
590        assert_eq!(fontconfig_family("sans-serif"), r"sans\-serif");
591        assert_eq!(fontconfig_family(r"a\b:c,d-e"), r"a\\b\:c\,d\-e");
592        assert_eq!(fontconfig_family(r"\\"), r"\\\\");
593        assert_eq!(fontconfig_family(""), "");
594        assert_eq!(
595            fontconfig_family("Noto Sans CJK 日本"),
596            "Noto Sans CJK 日本"
597        );
598    }
599
600    /// M6-03: the platform's ask runs a subprocess (`fc-match` on Linux,
601    /// with a 2 s timeout), so a look-up of a cached family, and the ask for
602    /// another one, must not wait for an ask in flight. The first asker
603    /// blocks until the test releases it; the other two must finish first.
604    #[cfg(feature = "system-fonts")]
605    #[test]
606    fn a_family_ask_in_flight_blocks_no_other_look_up() {
607        use std::sync::mpsc;
608        use std::time::Duration;
609        const GENEROUS: Duration = Duration::from_secs(10);
610
611        let asked = std::sync::Arc::new(AskedFamilies::default());
612        asked
613            .lock()
614            .unwrap()
615            .insert("Cached".to_owned(), Some("Cached substitute".to_owned()));
616
617        let (started_tx, started) = mpsc::channel();
618        let (release, release_rx) = mpsc::channel::<()>();
619        let first = std::thread::spawn({
620            let asked = asked.clone();
621            move || {
622                asked_once(&asked, "First", |_| {
623                    let _ = started_tx.send(());
624                    let _ = release_rx.recv();
625                    Some("First substitute".to_owned())
626                })
627            }
628        });
629        started
630            .recv_timeout(GENEROUS)
631            .expect("the first ask never started");
632
633        let (done_tx, done) = mpsc::channel();
634        let others = std::thread::spawn({
635            let asked = asked.clone();
636            move || {
637                let cached = asked_once(&asked, "Cached", |_| Some("asked again".to_owned()));
638                let _ = done_tx.send(("Cached", cached));
639                let second = asked_once(&asked, "Second", |_| Some("Second substitute".to_owned()));
640                let _ = done_tx.send(("Second", second));
641            }
642        });
643        let while_in_flight: Vec<_> = (0..2)
644            .map_while(|_| done.recv_timeout(GENEROUS).ok())
645            .collect();
646
647        release.send(()).unwrap();
648        assert_eq!(first.join().unwrap().as_deref(), Some("First substitute"));
649        others.join().unwrap();
650        assert_eq!(
651            while_in_flight,
652            [
653                ("Cached", Some("Cached substitute".to_owned())),
654                ("Second", Some("Second substitute".to_owned())),
655            ],
656            "a look-up waited for another family's ask"
657        );
658        assert_eq!(
659            asked_once(&asked, "First", |_| None).as_deref(),
660            Some("First substitute"),
661            "the first ask's answer is kept"
662        );
663    }
664
665    #[cfg(feature = "system-fonts")]
666    mod system {
667        use super::super::*;
668
669        /// A family no system has is drawn in fontconfig's best match, a
670        /// family the system has, so its substitute is itself `None`. On a
671        /// fontconfig platform where `fc-match` cannot be run, and on every
672        /// other platform, there is no substitute.
673        #[test]
674        fn a_missing_family_has_a_substitute_the_system_has() {
675            let missing = format!("native-theme-no-such-family-{}", std::process::id());
676            let substitute = substitute_family(&missing);
677            let fontconfig_platform = cfg!(all(
678                unix,
679                not(target_os = "macos"),
680                not(target_os = "ios"),
681                not(target_os = "android")
682            ));
683            let fc_match_runs = std::process::Command::new("fc-match")
684                .arg("--version")
685                .output()
686                .is_ok_and(|output| output.status.success());
687            if !(fontconfig_platform && fc_match_runs) {
688                println!(
689                    "a_missing_family_has_a_substitute_the_system_has: fc-match not run here, \
690                     substitute {substitute:?}"
691                );
692                assert_eq!(substitute, None);
693                return;
694            }
695            let substitute = substitute.expect("fc-match names a substitute");
696            assert!(
697                system_face(&substitute, 400, FontStyle::Normal).is_some(),
698                "the substitute {substitute:?} has a system face"
699            );
700            assert_eq!(substitute_family(&substitute), None);
701        }
702
703        /// Never substituted: a family no system has is `None`.
704        #[test]
705        fn a_family_no_system_has_is_none() {
706            assert_eq!(
707                system_face("native-theme-no-such-family-7f3c1a", 400, FontStyle::Normal),
708                None
709            );
710        }
711
712        /// A name that differs only in case matches, and the face reports
713        /// the family as fontdb records it, not as asked. The family is
714        /// taken from the loaded database itself, so the clause holds on
715        /// every runner that has a font with a lower-case letter in its
716        /// family name; a runner with none fails here, and says so.
717        #[test]
718        fn a_family_matches_caselessly_and_reports_its_recorded_name() {
719            let db = database();
720            let (recorded, weight, style) = db
721                .faces()
722                .find_map(|info| {
723                    let (name, _) = info.families.first()?;
724                    name.chars()
725                        .any(char::is_lowercase)
726                        .then(|| (name.clone(), info.weight.0, style_of(info.style)))
727                })
728                .expect("the font database holds a face whose family has a lower-case letter");
729            let asked = recorded.to_uppercase();
730            assert_ne!(asked, recorded);
731            let face = system_face(&asked, weight, style)
732                .expect("the upper-cased family name finds the face");
733            assert_ne!(
734                face.family.as_ref(),
735                asked.as_str(),
736                "not the spelling asked for"
737            );
738            let recorded_by_a_face_of_that_family = db.faces().any(|info| {
739                info.families
740                    .first()
741                    .is_some_and(|(first, _)| **first == *face.family)
742                    && info.families.iter().any(|(name, _)| {
743                        unicase::UniCase::new(name.as_str())
744                            == unicase::UniCase::new(recorded.as_str())
745                    })
746            });
747            assert!(
748                recorded_by_a_face_of_that_family,
749                "the family fontdb records for the face"
750            );
751        }
752
753        /// Two calls with the same arguments return the same face.
754        #[test]
755        fn the_same_query_gives_the_same_face() {
756            let info = database()
757                .faces()
758                .next()
759                .expect("the font database holds a face");
760            let (name, _) = info.families.first().expect("a face records a family");
761            let a = system_face(name, info.weight.0, style_of(info.style));
762            let b = system_face(name, info.weight.0, style_of(info.style));
763            assert!(a.is_some());
764            assert_eq!(a, b);
765        }
766
767        /// The file route: "SF Pro" and Core Text's family name both give
768        /// the face whose family is the first family the Core Text file's
769        /// first face records. The repository holds no font file a unit test
770        /// could load in the Core Text file's place, so this is the route's
771        /// only check; the screenshot workflow (`.github/workflows/screenshots.yml`)
772        /// runs the egui connector's `system_faces_resolve` on the macOS
773        /// runner too.
774        #[cfg(target_os = "macos")]
775        #[test]
776        fn the_macos_system_ui_font_is_found_by_its_file() {
777            let ui = crate::macos::system_ui_font(false)
778                .expect("Core Text names the system UI font's file");
779            let expected = {
780                let mut db = fontdb::Database::new();
781                db.load_font_file(&ui.path)
782                    .expect("the system UI font's file loads");
783                db.faces()
784                    .next()
785                    .and_then(|face| face.families.first().map(|(name, _)| name.clone()))
786                    .expect("the file records a family")
787            };
788            for asked in ["SF Pro", ui.family.as_str()] {
789                let face = system_face(asked, 400, FontStyle::Normal)
790                    .unwrap_or_else(|| panic!("{asked} resolves through Core Text"));
791                assert_eq!(face.family.as_ref(), expected.as_str());
792            }
793        }
794    }
795}