okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
15.0 KiB291 linesraw
1//! Linux: keep the colour emoji font that the AppImage's WebKitGTK cannot draw away from the app window (#4533).
2//!
3//! The WebKitGTK inside the AppImage paints a COLRv1 colour font through Skia, and its `colrv1_configure_skpaint` reads past the end of a
4//! gradient's colour-stop list. The library is built with libstdc++ range checks on, so the read becomes `abort()` and `WebKitWebProcess`
5//! dies: the window goes grey the first time a chat title or a message draws an emoji (Fedora 44 and newer Ubuntu ship
6//! `Noto-COLRv1.ttf` as the default colour emoji font; the reporters on #4533 name the same assertion and the same workaround).
7//!
8//! fontconfig reads one file when `FONTCONFIG_FILE` is set, and that file replaces the normal configuration, so the file written here
9//! includes the system configuration first and only then rejects the COLRv1 faces. Emoji are then drawn from whatever else the system
10//! has (the outline "Noto Emoji" is preferred); nothing else about the fonts changes.
11//!
12//! Only the window process is told (main.rs run_window_process, before WebKit starts its own processes). The shell owns the host, the
13//! engine and the agent, and they keep the fonts the person chose. A machine with no COLRv1 font is not touched at all.
14//!
15//! This file is plain std so its decisions are unit-tested on every platform; only the window process on Linux uses it.
16//! The idea is that of community PR #4485; the code is written for this tree.
17
18use std::path::{Path, PathBuf};
19
20/// File name patterns of the COLRv1 faces (fontconfig globs, case sensitive, so both spellings). Bitmap (`CBDT`) and outline faces are not
21/// listed: they draw fine, and hiding them would leave an empty box where an emoji should be.
22pub const COLRV1_GLOBS: &[&str] = &["*COLRv1*", "*colrv1*", "*COLRV1*"];
23
24/// The outline family preferred in place of the colour one.
25const OUTLINE_EMOJI: &str = "Noto Emoji";
26
27/// fontconfig's own configuration. `FONTCONFIG_FILE` replaces it, so the written file pulls it back in.
28pub const SYSTEM_CONFIG: &str = "/etc/fonts/fonts.conf";
29
30/// `STRATA_FONT_CONFIG=off` turns this off; `STRATA_FONT_CONFIG=/path/to/fonts.conf` uses the person's own file.
31const OFF: &str = "off";
32
33/// The name of the file written under the data folder.
34const FILE_NAME: &str = "fonts-no-colrv1.conf";
35
36/// Folders fontconfig scans by default, where a colour emoji font is found: the system ones, the person's own, and the XDG data folders.
37pub fn font_dirs(env: &dyn Fn(&str) -> Option<String>) -> Vec<PathBuf> {
38    let mut dirs = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")];
39    let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
40    match env("XDG_DATA_HOME").filter(|d| !d.is_empty()) {
41        Some(data) => dirs.push(PathBuf::from(data).join("fonts")),
42        None => {
43            if let Some(h) = &home {
44                dirs.push(h.join(".local/share/fonts"));
45            }
46        }
47    }
48    if let Some(h) = &home {
49        dirs.push(h.join(".fonts"));
50    }
51    if let Some(list) = env("XDG_DATA_DIRS") {
52        for d in list.split(':').filter(|d| !d.is_empty()) {
53            dirs.push(PathBuf::from(d).join("fonts"));
54        }
55    }
56    dirs.dedup();
57    dirs
58}
59
60/// A COLRv1 font file installed under `dirs`, if any. The scan is shallow and stops at the first one found, so a window that starts on a
61/// machine without such a font costs a few directory reads and nothing else.
62pub fn colrv1_font_present(dirs: &[PathBuf]) -> Option<PathBuf> {
63    fn scan(dir: &Path, depth: u8, found: &mut Option<PathBuf>) {
64        if found.is_some() || depth == 0 {
65            return;
66        }
67        let Ok(entries) = std::fs::read_dir(dir) else { return };
68        for entry in entries.flatten() {
69            let path = entry.path();
70            if path.is_dir() {
71                scan(&path, depth - 1, found);
72            }
73            else if path.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase().contains("colrv1")).unwrap_or(false) {
74                *found = Some(path);
75                return;
76            }
77            if found.is_some() {
78                return;
79            }
80        }
81    }
82    let mut found = None;
83    for dir in dirs {
84        scan(dir, 5, &mut found);
85        if found.is_some() {
86            break;
87        }
88    }
89    found
90}
91
92/// The configuration file's text: the system's own rules, then the rejection of the COLRv1 faces, then the outline family preferred.
93pub fn config_text(system_config: &str) -> String {
94    let mut lines: Vec<String> = vec![
95        "<?xml version=\"1.0\"?>".into(),
96        "<!DOCTYPE fontconfig SYSTEM \"urn:fontconfig:fonts.dtd\">".into(),
97        "<!-- Written by Strata for its own window only. The WebKitGTK inside the AppImage aborts while it draws a COLRv1 colour font,".into(),
98        "     so those faces are hidden from the window; every other font is the system's own setup, included first.".into(),
99        "     Off: STRATA_FONT_CONFIG=off. Your own file: set FONTCONFIG_FILE yourself. -->".into(),
100        "<fontconfig>".into(),
101        format!("  <include ignore_missing=\"yes\">{system_config}</include>"),
102        "  <selectfont>".into(),
103    ];
104    // fontconfig rejects a font only inside <selectfont>
105    for glob in COLRV1_GLOBS {
106        lines.push(format!("    <rejectfont><glob>{glob}</glob></rejectfont>"));
107    }
108    lines.push("  </selectfont>".into());
109    lines.push("  <alias binding=\"strong\">".into());
110    lines.push("    <family>Noto Color Emoji</family>".into());
111    lines.push(format!("    <prefer><family>{OUTLINE_EMOJI}</family></prefer>"));
112    lines.push("  </alias>".into());
113    lines.push("</fontconfig>".into());
114    lines.join("\n") + "\n"
115}
116
117/// Write the file under `dir` and return its path, or None when it cannot be written or there is no system configuration to include
118/// (then the window would be left without any font). Rewritten only when the contents differ, so a start-up touches the disk once, and a
119/// file left by an older Strata is put right. Written through a temporary file and moved, so a second instance starting at the same moment
120/// never hands fontconfig half a file.
121pub fn ensure_config(dir: &Path, system_config: &Path) -> Option<PathBuf> {
122    if !system_config.exists() {
123        return None;
124    }
125    std::fs::create_dir_all(dir).ok()?;
126    let path = dir.join(FILE_NAME);
127    let want = config_text(&system_config.to_string_lossy());
128    if matches!(std::fs::read_to_string(&path), Ok(have) if have == want) {
129        return Some(path);
130    }
131    let tmp = dir.join(format!("{FILE_NAME}.{}.tmp", std::process::id()));
132    std::fs::write(&tmp, want.as_bytes()).ok()?;
133    if std::fs::rename(&tmp, &path).is_err() {
134        let _ = std::fs::remove_file(&tmp);
135        // another writer got there first: take its file only if it is the one wanted
136        return (std::fs::read_to_string(&path).ok()? == want).then_some(path);
137    }
138    Some(path)
139}
140
141/// The file the window process should hand to fontconfig, or None to leave the environment exactly as it is. In this order, so a person's
142/// own choice always wins and a machine without the font is untouched:
143///   1. `FONTCONFIG_FILE` already set: theirs.
144///   2. `STRATA_FONT_CONFIG=off`: nothing.
145///   3. `STRATA_FONT_CONFIG=<path>`: that file, when it exists.
146///   4. no COLRv1 font installed: nothing.
147pub fn config_for(env: &dyn Fn(&str) -> Option<String>, dir: &Path, dirs: &[PathBuf], system_config: &Path) -> Option<PathBuf> {
148    if env("FONTCONFIG_FILE").is_some() || env("STRATA_FONT_CONFIG").as_deref() == Some(OFF) {
149        return None;
150    }
151    if let Some(custom) = env("STRATA_FONT_CONFIG") {
152        let p = PathBuf::from(custom);
153        return p.is_file().then_some(p);
154    }
155    colrv1_font_present(dirs)?;
156    ensure_config(dir, system_config)
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    fn env_from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
164        let owned: Vec<(String, String)> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
165        move |k: &str| owned.iter().find(|(a, _)| a == k).map(|(_, v)| v.clone())
166    }
167
168    fn scratch(name: &str) -> PathBuf {
169        let dir = std::env::temp_dir().join(format!("strata-fontguard-{name}-{}", std::process::id()));
170        let _ = std::fs::remove_dir_all(&dir);
171        std::fs::create_dir_all(&dir).unwrap();
172        dir
173    }
174
175    #[test]
176    fn the_file_includes_the_system_config_first_and_rejects_only_colrv1_faces_inside_selectfont() {
177        let text = config_text("/etc/fonts/fonts.conf");
178        assert!(text.starts_with("<?xml"));
179        let include = text.find("/etc/fonts/fonts.conf").expect("the system's fonts are kept");
180        let select = text.find("<selectfont>").expect("a rejection needs <selectfont>");
181        let select_end = text.find("</selectfont>").expect("closed");
182        assert!(include < select && select < select_end);
183        assert_eq!(text.matches("<rejectfont>").count(), COLRV1_GLOBS.len());
184        for glob in COLRV1_GLOBS {
185            let at = text.find(&format!("<glob>{glob}</glob>")).unwrap_or_else(|| panic!("{glob} is rejected"));
186            assert!(at > select && at < select_end, "{glob} is inside <selectfont>");
187        }
188        // the bitmap and the outline faces stay
189        assert!(!text.contains("NotoColorEmoji.ttf") && !text.contains("NotoEmoji-Regular.ttf"));
190        assert!(text.contains("<prefer><family>Noto Emoji</family></prefer>"));
191        assert!(!text.contains('{') && !text.contains('}'), "no placeholder left: {text}");
192        // well formed enough: every opened tag is closed
193        for tag in ["fontconfig", "selectfont", "alias"] {
194            assert_eq!(text.matches(&format!("<{tag}")).count(), text.matches(&format!("</{tag}>")).count(), "{tag}");
195        }
196    }
197
198    #[test]
199    fn the_globs_match_the_real_file_names_and_not_the_faces_that_draw_fine() {
200        // fontconfig's glob is `*` anywhere; this is the same rule on the file names that matter
201        let hit = |name: &str| COLRV1_GLOBS.iter().any(|g| { let core = g.trim_matches('*'); name.contains(core) });
202        for bad in ["/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf", "/usr/share/fonts/truetype/noto/NotoColorEmoji-COLRv1.ttf",
203                    "/home/me/.fonts/Twemoji-colrv1.ttf", "/usr/share/fonts/NotoSansCOLRv1-Regular.ttf"] {
204            assert!(hit(bad), "{bad}");
205        }
206        for good in ["/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf", "/usr/share/fonts/truetype/noto/NotoEmoji-Regular.ttf",
207                     "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
208                     "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf"] {
209            assert!(!hit(good), "{good}");
210        }
211    }
212
213    #[test]
214    fn a_persons_own_fontconfig_or_an_opt_out_leaves_the_environment_alone() {
215        let dir = scratch("own");
216        let system = dir.join("system.conf");
217        std::fs::write(&system, b"<fontconfig/>").unwrap();
218        let fonts = dir.join("fonts");
219        std::fs::create_dir_all(&fonts).unwrap();
220        std::fs::write(fonts.join("Noto-COLRv1.ttf"), b"x").unwrap();
221        let dirs = vec![fonts];
222        assert_eq!(config_for(&env_from(&[("FONTCONFIG_FILE", "/home/me/fonts.conf")]), &dir, &dirs, &system), None);
223        assert_eq!(config_for(&env_from(&[("STRATA_FONT_CONFIG", "off")]), &dir, &dirs, &system), None);
224        let theirs = dir.join("theirs.conf");
225        std::fs::write(&theirs, b"<fontconfig/>").unwrap();
226        assert_eq!(config_for(&env_from(&[("STRATA_FONT_CONFIG", theirs.to_str().unwrap())]), &dir, &dirs, &system), Some(theirs));
227        assert_eq!(config_for(&env_from(&[("STRATA_FONT_CONFIG", "/no/such/fonts.conf")]), &dir, &dirs, &system), None);
228        // no setting at all: the font is there, so the file is written
229        assert!(config_for(&env_from(&[]), &dir.join("out"), &dirs, &system).is_some());
230        let _ = std::fs::remove_dir_all(&dir);
231    }
232
233    #[test]
234    fn a_machine_without_a_colrv1_font_is_not_touched() {
235        let dir = scratch("none");
236        let system = dir.join("system.conf");
237        std::fs::write(&system, b"<fontconfig/>").unwrap();
238        let fonts = dir.join("fonts");
239        std::fs::create_dir_all(fonts.join("noto")).unwrap();
240        std::fs::write(fonts.join("noto/NotoColorEmoji.ttf"), b"bitmap").unwrap();
241        std::fs::write(fonts.join("noto/NotoEmoji-Regular.ttf"), b"outline").unwrap();
242        std::fs::write(fonts.join("noto/NotoSansArabic-Regular.ttf"), b"arabic").unwrap();
243        assert_eq!(colrv1_font_present(&[fonts.clone()]), None);
244        assert_eq!(config_for(&env_from(&[]), &dir.join("out"), &[fonts.clone()], &system), None);
245        assert!(!dir.join("out").exists(), "nothing is written");
246        std::fs::write(fonts.join("noto/Noto-COLRv1.ttf"), b"colour").unwrap();
247        assert!(colrv1_font_present(&[fonts]).is_some());
248        let _ = std::fs::remove_dir_all(&dir);
249    }
250
251    #[test]
252    fn the_scan_is_shallow_and_a_missing_folder_is_fine() {
253        let dir = scratch("deep");
254        let mut deep = dir.clone();
255        for i in 0..9 { deep = deep.join(format!("d{i}")); }
256        std::fs::create_dir_all(&deep).unwrap();
257        std::fs::write(deep.join("Noto-COLRv1.ttf"), b"x").unwrap();
258        assert_eq!(colrv1_font_present(&[dir.clone(), dir.join("missing")]), None, "nine levels down is not a font folder");
259        let _ = std::fs::remove_dir_all(&dir);
260    }
261
262    #[test]
263    fn the_folders_follow_the_xdg_variables() {
264        let none = font_dirs(&env_from(&[("HOME", "/home/me")]));
265        assert!(none.contains(&PathBuf::from("/usr/share/fonts")));
266        assert!(none.contains(&PathBuf::from("/home/me/.local/share/fonts")));
267        assert!(none.contains(&PathBuf::from("/home/me/.fonts")));
268        let set = font_dirs(&env_from(&[("HOME", "/home/me"), ("XDG_DATA_HOME", "/data/me"), ("XDG_DATA_DIRS", "/usr/local/share:/var/lib/flatpak/exports/share")]));
269        assert!(set.contains(&PathBuf::from("/data/me/fonts")));
270        assert!(!set.contains(&PathBuf::from("/home/me/.local/share/fonts")));
271        assert!(set.contains(&PathBuf::from("/var/lib/flatpak/exports/share/fonts")));
272    }
273
274    #[test]
275    fn the_file_is_written_once_an_old_one_is_put_right_and_nothing_is_left_behind() {
276        let dir = scratch("write");
277        let system = dir.join("system.conf");
278        std::fs::write(&system, b"<fontconfig/>").unwrap();
279        let out = dir.join("out");
280        let first = ensure_config(&out, &system).expect("written");
281        assert_eq!(ensure_config(&out, &system).unwrap(), first, "the same path every start");
282        std::fs::write(&first, "<fontconfig/>").unwrap();
283        assert_eq!(ensure_config(&out, &system), Some(first.clone()));
284        assert_eq!(std::fs::read_to_string(&first).unwrap(), config_text(&system.to_string_lossy()));
285        assert_eq!(std::fs::read_dir(&out).unwrap().count(), 1, "one file, no temporary");
286        // no system configuration to include: nothing is written (the window would have no font at all)
287        assert_eq!(ensure_config(&dir.join("out2"), &dir.join("absent.conf")), None);
288        assert!(!dir.join("out2").exists());
289        let _ = std::fs::remove_dir_all(&dir);
290    }
291}