Skip to main content

cosmic_applet_avestruz/
fonts.rs

1// SPDX-License-Identifier: MIT
2
3//! Fonts: which ones emoji are drawn with.
4//!
5//! Text is shaped and drawn by `cosmic-text`, which rasterizes glyphs with
6//! `swash`. Left to itself it gets emoji wrong in two ways, and both are
7//! put right here, once, before anything is drawn (see [`prepare`]).
8//!
9//! **A font whose glyphs can't be drawn.** Of the ways a font can carry
10//! colour glyphs, `swash` draws bitmaps (`CBDT`, `sbix`) and the first
11//! version of layered outlines (`COLR` version 0). It does not draw the
12//! second (`COLR` version 1, with gradients), and a font that has only
13//! those gets its glyphs chosen all the same, since it says it has them:
14//! they come out as nothing at all. Some distributions ship their emoji
15//! font that way. Such fonts are taken out of the list this process
16//! chooses from, and what they would have drawn falls to the next font
17//! that has it.
18//!
19//! **A text font that comes first.** What the font of the interface has
20//! no glyph for is looked for in a list of other fonts, in order, and an
21//! emoji font is the last of that list: after text fonts that have a face
22//! or a heart of their own, in one colour. So a note would show some emoji
23//! in colour and some as line drawings. The fonts for emoji are put at the
24//! head of that list instead (see [`emoji_families`]): the ones in colour
25//! first, then any other that is one by its name. A font for emoji is
26//! one that has a glyph for a face ([`AN_EMOJI`]) and either colour or
27//! the name: a text font with a few emoji among its letters is not one,
28//! and neither is a font with colour glyphs that are no emoji.
29//!
30//! **A font of the applet's own.** Fonts in the `fonts` directory beside
31//! the event store (see [`own_fonts_dir`]) are read as well as the
32//! system's, and come before them. That is where to put an emoji font that
33//! can be drawn where the system's can't, without changing what any other
34//! program draws: `just emoji-font-setup` fetches one.
35//!
36//! Nothing is changed outside this process: no file, and no setting.
37
38use std::path::{Path, PathBuf};
39
40use cosmic::iced::advanced::graphics::text::cosmic_text::fontdb::{Database, ID, Source};
41use cosmic::iced::advanced::graphics::text::cosmic_text::skrifa::raw::TableProvider;
42use cosmic::iced::advanced::graphics::text::cosmic_text::skrifa::{FontRef, MetadataProvider, Tag};
43use cosmic::iced::advanced::graphics::text::cosmic_text::{Fallback, FontSystem, PlatformFallback};
44use cosmic::iced::advanced::graphics::text::font_system;
45use unicode_script::Script;
46
47/// Where the applet's own fonts are: the user's data directory, beside
48/// the event store.
49pub fn own_fonts_dir() -> PathBuf {
50    dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")).join("cosmic-applet-avestruz").join("fonts")
51}
52
53/// An emoji every font for emoji has a glyph for, and few others: by
54/// which one is told.
55const AN_EMOJI: char = '😀';
56
57/// What a face has of glyphs in colour.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59enum Colour {
60    /// None: an ordinary font.
61    None,
62    /// Some that can be drawn: bitmaps, or layered outlines of the first
63    /// kind.
64    Drawn,
65    /// Only ones that can't: layered outlines of the second kind, with
66    /// nothing to draw instead.
67    Undrawn,
68}
69
70/// What `font` has of glyphs in colour. Its `COLR` table lists the glyphs
71/// of the first kind, and says of which version it is: of version 1 or
72/// later with none listed that way, and no bitmaps beside it, there is
73/// nothing to draw.
74fn colour(font: &FontRef) -> Colour {
75    if [b"CBDT", b"sbix"].into_iter().any(|bitmaps| font.table_data(Tag::new(bitmaps)).is_some()) {
76        return Colour::Drawn;
77    }
78    match font.colr() {
79        Ok(colr) if colr.num_base_glyph_records() > 0 => Colour::Drawn,
80        Ok(colr) if colr.version() >= 1 => Colour::Undrawn,
81        _ => Colour::None,
82    }
83}
84
85/// What the face numbered `index` of the font file `data` has of glyphs
86/// in colour, and whether it has emoji: `None` of a file that is no font.
87fn read(data: &[u8], index: u32) -> Option<(Colour, bool)> {
88    let font = FontRef::from_index(data, index).ok()?;
89    Some((colour(&font), font.charmap().map(AN_EMOJI).is_some()))
90}
91
92/// A face, as far as choosing the fonts for emoji goes.
93#[derive(Debug, Clone, PartialEq, Eq)]
94struct Face {
95    id: ID,
96    /// What its family is called.
97    family: String,
98    colour: Colour,
99    /// It has emoji: a glyph for [`AN_EMOJI`].
100    has_emoji: bool,
101    /// It says of itself that it is for emoji: its name does.
102    for_emoji: bool,
103    /// It is one of the applet's own (see [`own_fonts_dir`]).
104    own: bool,
105}
106
107/// Every face of `fonts`, with those under `own` marked as the applet's.
108fn faces(fonts: &Database, own: &Path) -> Vec<Face> {
109    let known: Vec<Face> = fonts
110        .faces()
111        .map(|face| Face {
112            id: face.id,
113            family: face.families.first().map_or_else(|| face.post_script_name.clone(), |(family, _)| family.clone()),
114            colour: Colour::None,
115            has_emoji: false,
116            for_emoji: face.post_script_name.contains("Emoji"),
117            own: match &face.source {
118                Source::File(path) | Source::SharedFile(path, _) => path.starts_with(own),
119                Source::Binary(_) => false,
120            },
121        })
122        .collect();
123    known
124        .into_iter()
125        .map(|face| {
126            let (colour, has_emoji) = fonts.with_face_data(face.id, read).flatten().unwrap_or((Colour::None, false));
127            Face { colour, has_emoji, ..face }
128        })
129        .collect()
130}
131
132/// The families emoji are to be looked for in before any other, in that
133/// order, of `faces`: those that have emoji in colour that can be drawn,
134/// the applet's own before the system's, then those that have them in
135/// one colour and are for emoji by their name. Each once. A font with
136/// colour glyphs and no emoji is not one, nor is a text font that has a
137/// few emoji among its letters; and none whose glyphs can't be drawn.
138fn emoji_families(faces: &[Face]) -> Vec<String> {
139    // The lower, the sooner.
140    let rank = |face: &Face| match (face.has_emoji, face.colour, face.own, face.for_emoji) {
141        (true, Colour::Drawn, true, _) => Some(0),
142        (true, Colour::Drawn, false, _) => Some(1),
143        (true, Colour::None, _, true) => Some(2),
144        _ => None,
145    };
146    let mut ranked: Vec<(u8, &str)> = faces.iter().filter_map(|face| Some((rank(face)?, face.family.as_str()))).collect();
147    ranked.sort_by_key(|(rank, _)| *rank);
148    let mut families: Vec<String> = Vec::new();
149    for (_, family) in ranked {
150        if !families.iter().any(|known| known == family) {
151            families.push(family.to_string());
152        }
153    }
154    families
155}
156
157/// The fonts a glyph is looked for in when the font asked for has none:
158/// as the platform has them, with the fonts for emoji before the rest.
159struct EmojiFirst {
160    platform: PlatformFallback,
161    /// The fonts for emoji, then the platform's own list.
162    common: Vec<&'static str>,
163}
164
165impl EmojiFirst {
166    /// With `emoji`, the families of the fonts for emoji, first. Their
167    /// names are kept for as long as the process runs, which is how long
168    /// the list is used: this is done once.
169    fn new(emoji: Vec<String>) -> Self {
170        let platform = PlatformFallback;
171        let mut common: Vec<&'static str> = emoji.into_iter().map(|family| &*Box::leak(family.into_boxed_str())).collect();
172        for family in platform.common_fallback() {
173            if !common.contains(family) {
174                common.push(family);
175            }
176        }
177        Self { platform, common }
178    }
179}
180
181impl Fallback for EmojiFirst {
182    fn common_fallback(&self) -> &[&'static str] {
183        &self.common
184    }
185
186    fn forbidden_fallback(&self) -> &[&'static str] {
187        self.platform.forbidden_fallback()
188    }
189
190    fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
191        self.platform.script_fallback(script, locale)
192    }
193}
194
195/// See that emoji are drawn, and with the fonts for emoji: read the
196/// applet's own fonts, take out the fonts whose colour glyphs can't be
197/// drawn, and have the fonts for emoji looked in before the others. To be
198/// called once, before any text is laid out. See the [module docs](self).
199pub fn prepare() {
200    let Ok(mut system) = font_system().write() else {
201        return;
202    };
203    let system = system.raw();
204    let own = own_fonts_dir();
205    let fonts = system.db_mut();
206    fonts.load_fonts_dir(&own);
207
208    let faces = faces(fonts, &own);
209    for face in faces.iter().filter(|face| face.colour == Colour::Undrawn) {
210        tracing::info!("{} is left out: its colour glyphs are of a kind that can't be drawn here (COLR version 1)", face.family);
211        fonts.remove_face(face.id);
212    }
213
214    let emoji = emoji_families(&faces);
215    if emoji.is_empty() {
216        return;
217    }
218    tracing::info!("emoji are looked for in {emoji:?} before any other font");
219    // The list of fonts to fall back to is given to the text system when
220    // it is made, and not after: so it is made again, of the same fonts.
221    let emptied = FontSystem::new_with_locale_and_db(String::new(), Database::new());
222    let (locale, fonts) = std::mem::replace(system, emptied).into_locale_and_db();
223    *system = FontSystem::new_with_locale_and_db_and_fallback(locale, fonts, EmojiFirst::new(emoji));
224}
225
226#[cfg(test)]
227mod tests {
228    use super::{AN_EMOJI, Colour, EmojiFirst, Face, emoji_families, read};
229    use cosmic::iced::advanced::graphics::text::cosmic_text::fontdb::ID;
230    use cosmic::iced::advanced::graphics::text::cosmic_text::{Fallback, PlatformFallback};
231
232    /// A font file with the `tables` named, each with what is in it.
233    fn font(tables: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
234        // The tables are listed in the order of their names, as a font
235        // file has them.
236        let mut tables = tables.to_vec();
237        tables.sort_by_key(|(tag, _)| **tag);
238        let mut file = vec![0, 1, 0, 0, 0, tables.len() as u8, 0, 0, 0, 0, 0, 0];
239        let mut at = file.len() + tables.len() * 16;
240        for (tag, content) in &tables {
241            file.extend_from_slice(*tag);
242            file.extend_from_slice(&[0; 4]);
243            file.extend_from_slice(&(at as u32).to_be_bytes());
244            file.extend_from_slice(&(content.len() as u32).to_be_bytes());
245            at += content.len();
246        }
247        for (_, content) in &tables {
248            file.extend_from_slice(content);
249        }
250        file
251    }
252
253    /// A `COLR` table of `version`, listing `as_version_0` glyphs the way
254    /// version 0 does: its header, which is all that is read of it, as
255    /// long as that version has it.
256    fn colr(version: u16, as_version_0: u16) -> Vec<u8> {
257        let mut table = [version.to_be_bytes(), as_version_0.to_be_bytes()].concat();
258        table.resize(if version == 0 { 14 } else { 34 }, 0);
259        table
260    }
261
262    /// A `cmap` table with a glyph for `character` and for no other.
263    fn cmap(character: char) -> Vec<u8> {
264        let code = (character as u32).to_be_bytes();
265        let mut table = vec![0, 0, 0, 1];
266        // One list of characters, for Unicode in full, right after this.
267        table.extend_from_slice(&[0, 3, 0, 10, 0, 0, 0, 12]);
268        // Of the kind that lists runs of characters: one run, of one.
269        table.extend_from_slice(&[0, 12, 0, 0, 0, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 1]);
270        table.extend_from_slice(&[code, code, 1u32.to_be_bytes()].concat());
271        table
272    }
273
274    #[test]
275    fn a_font_with_only_gradient_colour_glyphs_cannot_be_drawn() {
276        let colour = |tables: &[(&[u8; 4], &[u8])]| read(&font(tables), 0).map(|(colour, _)| colour);
277        assert_eq!(colour(&[(b"cmap", &cmap('a')), (b"COLR", &colr(1, 0))]), Some(Colour::Undrawn));
278
279        // No colour glyphs at all: an ordinary font.
280        assert_eq!(colour(&[(b"cmap", &cmap('a')), (b"glyf", &[0; 8])]), Some(Colour::None));
281        assert_eq!(colour(&[(b"COLR", &colr(0, 0))]), Some(Colour::None), "a list of none");
282        // Layered outlines of the first kind, alone or beside the second.
283        assert_eq!(colour(&[(b"COLR", &colr(0, 120))]), Some(Colour::Drawn));
284        assert_eq!(colour(&[(b"COLR", &colr(1, 120))]), Some(Colour::Drawn));
285        // Bitmaps, alone or to draw instead.
286        assert_eq!(colour(&[(b"cmap", &cmap('a')), (b"CBDT", &[0; 4])]), Some(Colour::Drawn));
287        assert_eq!(colour(&[(b"COLR", &colr(1, 0)), (b"CBDT", &[0; 4])]), Some(Colour::Drawn));
288        assert_eq!(colour(&[(b"sbix", &[0; 4]), (b"COLR", &colr(1, 0))]), Some(Colour::Drawn));
289        // A table cut short says nothing.
290        assert_eq!(colour(&[(b"COLR", &[0, 1])]), Some(Colour::None));
291    }
292
293    #[test]
294    fn a_font_has_emoji_if_it_has_a_glyph_for_one() {
295        let has_emoji = |tables: &[(&[u8; 4], &[u8])]| read(&font(tables), 0).map(|(_, has_emoji)| has_emoji);
296        assert_eq!(has_emoji(&[(b"cmap", &cmap(AN_EMOJI)), (b"CBDT", &[0; 4])]), Some(true));
297        assert_eq!(has_emoji(&[(b"cmap", &cmap('a')), (b"CBDT", &[0; 4])]), Some(false));
298        assert_eq!(has_emoji(&[(b"CBDT", &[0; 4])]), Some(false), "no list of characters at all");
299    }
300
301    #[test]
302    fn a_file_that_is_no_font_says_nothing() {
303        for file in [&b""[..], b"not a font", &[0, 1, 0, 0, 0, 9]] {
304            assert_eq!(read(file, 0), None, "{file:?}");
305        }
306        // A font file has one face, and no second.
307        let one = font(&[(b"cmap", &cmap(AN_EMOJI)), (b"COLR", &colr(1, 0))]);
308        assert_eq!(read(&one, 0), Some((Colour::Undrawn, true)));
309        assert_eq!(read(&one, 1), None);
310    }
311
312    /// Faces called `families`, each with what it has of colour, whether
313    /// it has emoji, whether it is for emoji by its name, and whether it
314    /// is the applet's own.
315    fn faces(families: &[(&str, Colour, bool, bool, bool)]) -> Vec<Face> {
316        families
317            .iter()
318            .map(|(family, colour, has_emoji, for_emoji, own)| Face {
319                id: ID::dummy(),
320                family: (*family).to_string(),
321                colour: *colour,
322                has_emoji: *has_emoji,
323                for_emoji: *for_emoji,
324                own: *own,
325            })
326            .collect()
327    }
328
329    #[test]
330    fn emoji_are_looked_for_in_colour_first_and_in_the_applets_own_font_before_the_systems() {
331        let installed = faces(&[
332            // A text font with a few emoji among its letters.
333            ("DejaVu Sans", Colour::None, true, false, false),
334            ("Noto Emoji", Colour::None, true, true, false),
335            ("Noto Color Emoji", Colour::Undrawn, true, true, false),
336            // A font with colour glyphs that are no emoji.
337            ("Mezenets Unicode", Colour::Drawn, false, false, false),
338            ("Twemoji", Colour::Drawn, true, false, false),
339            ("Twemoji", Colour::Drawn, true, false, false),
340            ("Bitmap Emoji", Colour::Drawn, true, true, true),
341        ]);
342        // The applet's own, the system's in colour, then the one in one
343        // colour; no text font, and not the one that can't be drawn.
344        assert_eq!(emoji_families(&installed), ["Bitmap Emoji", "Twemoji", "Noto Emoji"]);
345
346        // A family with a face that can be drawn and one that can't, as
347        // when the applet's own font is called what the system's is: it
348        // is the one that can be drawn that is left to find by that name.
349        let both = faces(&[
350            ("Noto Color Emoji", Colour::Undrawn, true, true, false),
351            ("Noto Color Emoji", Colour::Drawn, true, true, true),
352        ]);
353        assert_eq!(emoji_families(&both), ["Noto Color Emoji"]);
354
355        assert!(emoji_families(&faces(&[("DejaVu Sans", Colour::None, true, false, false)])).is_empty());
356        assert!(emoji_families(&faces(&[("Noto Color Emoji", Colour::Undrawn, true, true, false)])).is_empty());
357    }
358
359    #[test]
360    fn the_fonts_for_emoji_come_before_the_platforms_and_the_rest_is_the_platforms() {
361        let platform = PlatformFallback;
362        let first = EmojiFirst::new(vec!["Bitmap Emoji".into(), "Noto Color Emoji".into()]);
363
364        let common = first.common_fallback();
365        assert_eq!(common[..2], ["Bitmap Emoji", "Noto Color Emoji"]);
366        // Every one of the platform's is still there, in its order, and
367        // none twice.
368        let rest: Vec<&str> = platform.common_fallback().iter().copied().filter(|family| *family != "Noto Color Emoji").collect();
369        assert_eq!(common[2..], rest[..]);
370        assert!(rest.contains(&"DejaVu Sans"));
371
372        assert_eq!(first.forbidden_fallback(), platform.forbidden_fallback());
373        let script = unicode_script::Script::Arabic;
374        assert_eq!(first.script_fallback(script, "en"), platform.script_fallback(script, "en"));
375    }
376}