Skip to main content

subspace_shell/
bundled_fonts.rs

1//! Fonts an app embeds and registers with the text system at startup, so a
2//! theme that names them draws the same faces on every platform, and in every
3//! screenshot, without the fonts being installed.
4//!
5//! A registered family counts as installed when a theme or Settings asks for
6//! it by name. Automatic font choices skip the families only the app
7//! provides, so themes that name no font keep the platform's fonts.
8
9use std::borrow::Cow;
10
11use gpui_kit::{App, Global};
12
13/// One embedded font file and the family it registers.
14///
15/// `family` is the font's typographic family (OpenType name ID 16, or name
16/// ID 1 when it has none): the name themes and Settings use, and the one the
17/// text systems group the file's face under. Embed static files, one per
18/// weight and style: the macOS text system registers a variable font as a
19/// single face at its default weight.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct BundledFont {
22    pub family: &'static str,
23    pub bytes: &'static [u8],
24}
25
26impl BundledFont {
27    /// A font file for `family`, usually from `include_bytes!`.
28    // qual:api (apps list their embedded files with it)
29    pub const fn new(family: &'static str, bytes: &'static [u8]) -> Self {
30        Self { family, bytes }
31    }
32}
33
34/// The families the app registered, and those of them the platform did not
35/// already provide.
36#[derive(Clone, Debug, Default, PartialEq, Eq)]
37struct BundledFamilies {
38    registered: Vec<String>,
39    bundled_only: Vec<String>,
40}
41
42impl Global for BundledFamilies {}
43
44/// Registers the app's fonts before the theme is applied. Returns a notice
45/// when the platform refuses them; themes then fall back as they do for any
46/// family that is not installed.
47pub(crate) fn register(fonts: &'static [BundledFont], cx: &mut App) -> Option<String> {
48    let platform = cx.text_system().all_font_names();
49    let result = cx
50        .text_system()
51        .add_fonts(font_data(fonts))
52        .map_err(|error| error.to_string());
53    record(result, families(fonts, &platform), cx)
54}
55
56/// The families registered at startup. They count as installed.
57pub(crate) fn registered(cx: &App) -> Vec<String> {
58    stored(cx).registered
59}
60
61/// The registered families the platform did not provide, which automatic
62/// font choices skip.
63pub(crate) fn bundled_only(cx: &App) -> Vec<String> {
64    stored(cx).bundled_only
65}
66
67fn stored(cx: &App) -> BundledFamilies {
68    cx.try_global::<BundledFamilies>()
69        .cloned()
70        .unwrap_or_default()
71}
72
73/// `names` without the `skipped` families, compared without case.
74pub(crate) fn without(names: &[String], skipped: &[String]) -> Vec<String> {
75    names
76        .iter()
77        .filter(|name| !skipped.iter().any(|skip| skip.eq_ignore_ascii_case(name)))
78        .cloned()
79        .collect()
80}
81
82fn font_data(fonts: &'static [BundledFont]) -> Vec<Cow<'static, [u8]>> {
83    fonts.iter().map(|font| Cow::Borrowed(font.bytes)).collect()
84}
85
86/// Each family once, in the order first listed, and which of them
87/// `platform` (the families before registration) lacks.
88fn families(fonts: &[BundledFont], platform: &[String]) -> BundledFamilies {
89    let mut registered: Vec<String> = Vec::new();
90    for font in fonts {
91        if !registered
92            .iter()
93            .any(|family| family.as_str() == font.family)
94        {
95            registered.push(font.family.to_owned());
96        }
97    }
98    let bundled_only = registered
99        .iter()
100        .filter(|family| {
101            !platform
102                .iter()
103                .any(|name| name.eq_ignore_ascii_case(family))
104        })
105        .cloned()
106        .collect();
107    BundledFamilies {
108        registered,
109        bundled_only,
110    }
111}
112
113fn record(result: Result<(), String>, families: BundledFamilies, cx: &mut App) -> Option<String> {
114    match result {
115        Ok(()) => {
116            cx.set_global(families);
117            None
118        }
119        Err(error) => Some(format!("The app's bundled fonts are unavailable: {error}")),
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use gpui_kit::TestAppContext;
126
127    use super::{
128        BundledFamilies, BundledFont, bundled_only, families, record, register, registered, without,
129    };
130
131    /// Fictional families: the test text system loads no font data.
132    const FIXTURE: &[BundledFont] = &[
133        BundledFont::new("Example Sans", b"regular"),
134        BundledFont::new("Example Sans", b"bold"),
135        BundledFont::new("Example Mono", b"mono"),
136    ];
137
138    fn names(values: &[&str]) -> Vec<String> {
139        values.iter().map(|value| (*value).to_owned()).collect()
140    }
141
142    #[test]
143    fn each_family_is_listed_once_and_platform_families_are_not_bundled_only() {
144        let found = families(FIXTURE, &names(&["example mono", "Menlo"]));
145
146        assert_eq!(found.registered, names(&["Example Sans", "Example Mono"]));
147        assert_eq!(found.bundled_only, names(&["Example Sans"]));
148        assert_eq!(
149            families(&[], &names(&["Menlo"])),
150            BundledFamilies::default()
151        );
152    }
153
154    #[test]
155    fn automatic_choices_skip_bundled_only_families_without_case() {
156        let installed = names(&["Example Sans", "Menlo", ".SystemUIFont"]);
157
158        assert_eq!(
159            without(&installed, &names(&["example sans"])),
160            names(&["Menlo", ".SystemUIFont"])
161        );
162        assert_eq!(without(&installed, &[]), installed);
163    }
164
165    #[gpui_kit::test]
166    fn registered_families_count_as_installed(cx: &mut TestAppContext) {
167        cx.update(|cx| {
168            assert!(registered(cx).is_empty(), "nothing before registration");
169
170            assert_eq!(register(FIXTURE, cx), None);
171
172            assert_eq!(registered(cx), names(&["Example Sans", "Example Mono"]));
173            assert_eq!(bundled_only(cx), names(&["Example Sans", "Example Mono"]));
174        });
175    }
176
177    #[gpui_kit::test]
178    fn a_refused_registration_reports_it_and_registers_nothing(cx: &mut TestAppContext) {
179        cx.update(|cx| {
180            let notice = record(Err("refused".into()), families(FIXTURE, &[]), cx);
181
182            assert!(notice.is_some_and(|notice| notice.contains("refused")));
183            assert!(registered(cx).is_empty());
184            assert!(bundled_only(cx).is_empty());
185        });
186    }
187}