1use 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
47pub fn own_fonts_dir() -> PathBuf {
50 dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")).join("cosmic-applet-avestruz").join("fonts")
51}
52
53const AN_EMOJI: char = '😀';
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59enum Colour {
60 None,
62 Drawn,
65 Undrawn,
68}
69
70fn 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
85fn 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#[derive(Debug, Clone, PartialEq, Eq)]
94struct Face {
95 id: ID,
96 family: String,
98 colour: Colour,
99 has_emoji: bool,
101 for_emoji: bool,
103 own: bool,
105}
106
107fn 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
132fn emoji_families(faces: &[Face]) -> Vec<String> {
139 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
157struct EmojiFirst {
160 platform: PlatformFallback,
161 common: Vec<&'static str>,
163}
164
165impl EmojiFirst {
166 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
195pub 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 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 fn font(tables: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
234 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 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 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 table.extend_from_slice(&[0, 3, 0, 10, 0, 0, 0, 12]);
268 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 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 assert_eq!(colour(&[(b"COLR", &colr(0, 120))]), Some(Colour::Drawn));
284 assert_eq!(colour(&[(b"COLR", &colr(1, 120))]), Some(Colour::Drawn));
285 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 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 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 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 ("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 ("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 assert_eq!(emoji_families(&installed), ["Bitmap Emoji", "Twemoji", "Noto Emoji"]);
345
346 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 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}