BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / linux_fonts.rs

linux_fonts.rs

linux_fonts.rs 8.0 KiB Download Raw
1//! Hide a system Noto Color Emoji face before GPUI loads fonts.
2//!
3//! Cosmic Text on Linux falls back to the family "Noto Color Emoji", and
4//! fontdb returns the first face of that name. A COLRv1-only face draws
5//! blank. The app bundles a CBDT build of the same name and loads it with
6//! `add_fonts`. fontdb only honors `<dir>` entries from `FONTCONFIG_FILE`,
7//! so this module rewrites those directories and leaves the system color
8//! emoji file out. An existing `FONTCONFIG_FILE` is left alone.
9
10use std::collections::HashSet;
11use std::fs;
12use std::path::{Path, PathBuf};
13
14const FONT_EXTENSIONS: &[&str] = &["ttf", "ttc", "otf", "otc"];
15
16/// A system color-emoji file that would win the "Noto Color Emoji" lookup.
17pub fn is_system_color_emoji_file(name: &str) -> bool {
18 let lower = name.to_ascii_lowercase();
19 let stem = lower
20 .rsplit_once('.')
21 .map(|(stem, _)| stem)
22 .unwrap_or(lower.as_str());
23 stem == "notocoloremoji"
24 || stem.starts_with("notocoloremoji-")
25 || (stem.contains("noto") && stem.contains("colrv1"))
26}
27
28/// Point `FONTCONFIG_FILE` at a font list that omits the system color emoji face.
29pub fn hide_system_color_emoji() {
30 if std::env::var_os("FONTCONFIG_FILE").is_some() {
31 log::info!("FONTCONFIG_FILE is already set, leaving the system emoji font alone");
32 return;
33 }
34 let Some(cache) = directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) else {
35 return;
36 };
37 let staging = cache.cache_dir().join("fontconfig-emoji");
38 let _ = fs::remove_dir_all(&staging);
39 if fs::create_dir_all(&staging).is_err() {
40 return;
41 }
42 let dirs: Vec<PathBuf> = font_roots()
43 .into_iter()
44 .enumerate()
45 .filter_map(|(index, root)| publish_root(&root, &staging, index))
46 .collect();
47 if dirs.is_empty() {
48 return;
49 }
50 let config = staging.join("fonts.conf");
51 if write_config(&config, &dirs).is_err() {
52 return;
53 }
54 unsafe { std::env::set_var("FONTCONFIG_FILE", &config) };
55 log::info!("emoji fontconfig {}", config.display());
56}
57
58fn font_roots() -> Vec<PathBuf> {
59 let mut roots = Vec::new();
60 let data_dirs =
61 std::env::var("XDG_DATA_DIRS").unwrap_or_else(|_| "/usr/local/share:/usr/share".to_owned());
62 for dir in data_dirs.split(':').filter(|dir| !dir.is_empty()) {
63 roots.push(PathBuf::from(dir).join("fonts"));
64 }
65 if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
66 roots.push(PathBuf::from(xdg).join("fonts"));
67 } else if let Ok(home) = std::env::var("HOME") {
68 roots.push(PathBuf::from(home).join(".local/share/fonts"));
69 }
70 if let Ok(home) = std::env::var("HOME") {
71 roots.push(PathBuf::from(home).join(".fonts"));
72 }
73 roots.retain(|path| path.is_dir());
74 roots.sort();
75 roots.dedup();
76 roots
77}
78
79/// Use `root` as-is when it has no color emoji file. Otherwise mirror it and skip that file.
80pub(crate) fn publish_root(root: &Path, staging: &Path, index: usize) -> Option<PathBuf> {
81 if !contains_emoji(root) {
82 return Some(root.to_path_buf());
83 }
84 let dest = staging.join(format!("root-{index}"));
85 let mut seen = HashSet::new();
86 mirror(root, &dest, &mut seen).then_some(dest)
87}
88
89fn contains_emoji(dir: &Path) -> bool {
90 fn walk(dir: &Path, seen: &mut HashSet<PathBuf>) -> bool {
91 let canon = fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
92 if !seen.insert(canon) {
93 return false;
94 }
95 let Ok(entries) = fs::read_dir(dir) else {
96 return false;
97 };
98 for entry in entries.flatten() {
99 let path = entry.path();
100 let Ok(meta) = fs::metadata(&path) else {
101 continue;
102 };
103 if meta.is_dir() {
104 if walk(&path, seen) {
105 return true;
106 }
107 } else if is_system_color_emoji_file(&entry.file_name().to_string_lossy()) {
108 return true;
109 }
110 }
111 false
112 }
113 walk(dir, &mut HashSet::new())
114}
115
116fn mirror(src: &Path, dest: &Path, seen: &mut HashSet<PathBuf>) -> bool {
117 let canon = fs::canonicalize(src).unwrap_or_else(|_| src.to_path_buf());
118 if !seen.insert(canon) {
119 return false;
120 }
121 let Ok(entries) = fs::read_dir(src) else {
122 return false;
123 };
124 let mut wrote = false;
125 for entry in entries.flatten() {
126 let path = entry.path();
127 let name = entry.file_name();
128 let Ok(meta) = fs::metadata(&path) else {
129 continue;
130 };
131 if meta.is_dir() {
132 if contains_emoji(&path) {
133 let child = dest.join(&name);
134 let _ = fs::create_dir_all(&child);
135 wrote |= mirror(&path, &child, seen);
136 } else {
137 let _ = fs::create_dir_all(dest);
138 wrote |= symlink_to(&path, &dest.join(&name)).is_ok();
139 }
140 } else if is_font_file(&name.to_string_lossy())
141 && !is_system_color_emoji_file(&name.to_string_lossy())
142 {
143 let _ = fs::create_dir_all(dest);
144 wrote |= symlink_to(&path, &dest.join(&name)).is_ok();
145 }
146 }
147 wrote
148}
149
150fn is_font_file(name: &str) -> bool {
151 name.rsplit_once('.').is_some_and(|(_, extension)| {
152 FONT_EXTENSIONS
153 .iter()
154 .any(|known| extension.eq_ignore_ascii_case(known))
155 })
156}
157
158fn symlink_to(target: &Path, link: &Path) -> std::io::Result<()> {
159 let target = fs::canonicalize(target).unwrap_or_else(|_| target.to_path_buf());
160 std::os::unix::fs::symlink(target, link)
161}
162
163fn write_config(path: &Path, dirs: &[PathBuf]) -> std::io::Result<()> {
164 let mut body = String::from("<?xml version=\"1.0\"?>\n<fontconfig>\n");
165 for dir in dirs {
166 body.push_str(" <dir>");
167 body.push_str(&xml_escape(&dir.to_string_lossy()));
168 body.push_str("</dir>\n");
169 }
170 body.push_str("</fontconfig>\n");
171 fs::write(path, body)
172}
173
174fn xml_escape(text: &str) -> String {
175 text.replace('&', "&amp;")
176 .replace('<', "&lt;")
177 .replace('>', "&gt;")
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 #[test]
185 fn color_emoji_file_names() {
186 assert!(is_system_color_emoji_file("NotoColorEmoji.ttf"));
187 assert!(is_system_color_emoji_file("Noto-COLRv1.ttf"));
188 assert!(is_system_color_emoji_file("NotoColorEmoji-emojicompat.ttf"));
189 assert!(!is_system_color_emoji_file("NotoSans-Regular.ttf"));
190 assert!(!is_system_color_emoji_file("NotoEmoji-Regular.ttf"));
191 }
192
193 #[test]
194 fn publish_root_drops_the_color_emoji_file_and_keeps_the_rest() {
195 let temp = tempfile::tempdir().unwrap();
196 let root = temp.path().join("fonts");
197 let noto = root.join("noto");
198 let other = root.join("liberation");
199 fs::create_dir_all(&noto).unwrap();
200 fs::create_dir_all(&other).unwrap();
201 fs::write(noto.join("NotoColorEmoji.ttf"), b"emoji").unwrap();
202 fs::write(noto.join("NotoSans-Regular.ttf"), b"sans").unwrap();
203 fs::write(other.join("LiberationSans.ttf"), b"serif").unwrap();
204 let staging = temp.path().join("staging");
205 fs::create_dir_all(&staging).unwrap();
206 let published = publish_root(&root, &staging, 0).unwrap();
207 assert!(published.starts_with(&staging));
208 assert!(!published.join("noto/NotoColorEmoji.ttf").exists());
209 assert_eq!(
210 fs::read(published.join("noto/NotoSans-Regular.ttf")).unwrap(),
211 b"sans"
212 );
213 assert_eq!(
214 fs::read(published.join("liberation/LiberationSans.ttf")).unwrap(),
215 b"serif"
216 );
217 }
218
219 #[test]
220 fn publish_root_keeps_a_tree_without_a_color_emoji_file() {
221 let temp = tempfile::tempdir().unwrap();
222 let root = temp.path().join("fonts");
223 fs::create_dir_all(&root).unwrap();
224 fs::write(root.join("DejaVuSans.ttf"), b"dejavu").unwrap();
225 let published = publish_root(&root, &temp.path().join("staging"), 0).unwrap();
226 assert_eq!(published, root);
227 }
228}