okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
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 > { 38let mut dirs =vec! [ PathBuf :: from ( "/usr/share/fonts" ), PathBuf :: from ( "/usr/local/share/fonts" )]; 39let home =env ( "HOME" ). filter ( |h| !h. is_empty ()). map ( PathBuf :: from); 40match env ( "XDG_DATA_HOME" ). filter ( |d| !d. is_empty ()) { 41Some ( data) => dirs. push ( PathBuf :: from ( data). join ( "fonts" )), 42None =>{ 43if let Some ( h) =& home{ 44 dirs. push ( h. join ( ".local/share/fonts" )); 45} 46} 47} 48if let Some ( h) =& home{ 49 dirs. push ( h. join ( ".fonts" )); 50} 51if let Some ( list) =env ( "XDG_DATA_DIRS" ) { 52for din 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 > { 63fn scan ( dir : & Path , depth : u8 , found : & mut Option < PathBuf >) { 64if found. is_some () || depth ==0 { 65return ; 66} 67let Ok ( entries) = std:: fs:: read_dir ( dir) else { return }; 68for entryin entries. flatten () { 69let path = entry. path (); 70if path. is_dir () { 71scan ( & path, depth -1 , found); 72} 73else if path. file_name (). map ( |n| n. to_string_lossy (). to_ascii_lowercase (). contains ( "colrv1" )). unwrap_or ( false ) { 74* found =Some ( path); 75return ; 76} 77if found. is_some () { 78return ; 79} 80} 81} 82let mut found =None ; 83for dirin dirs{ 84scan ( dir, 5 , & mut found); 85if found. is_some () { 86break ; 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 { 94let 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 (), 101format! ( " <include ignore_missing=\"yes\">{system_config}</include>" ), 102" <selectfont>" . into (), 103]; 104// fontconfig rejects a font only inside <selectfont> 105for globin 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 > { 122if !system_config. exists () { 123return None ; 124} 125 std:: fs:: create_dir_all ( dir). ok () ?; 126let path = dir. join ( FILE_NAME ); 127let want =config_text ( & system_config. to_string_lossy ()); 128if matches! ( std:: fs:: read_to_string ( & path), Ok ( have) if have == want) { 129return Some ( path); 130} 131let tmp = dir. join ( format! ( "{FILE_NAME}.{}.tmp" , std:: process:: id ())); 132 std:: fs:: write ( & tmp, want. as_bytes ()). ok () ?; 133if std:: fs:: rename ( & tmp, & path). is_err () { 134let _ = std:: fs:: remove_file ( & tmp); 135// another writer got there first: take its file only if it is the one wanted 136return ( std:: fs:: read_to_string ( & path). ok () ? == want). then_some ( path); 137} 138Some ( 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 > { 148if env ( "FONTCONFIG_FILE" ). is_some () ||env ( "STRATA_FONT_CONFIG" ). as_deref () ==Some ( OFF ) { 149return None ; 150} 151if let Some ( custom) =env ( "STRATA_FONT_CONFIG" ) { 152let p =PathBuf :: from ( custom); 153return p. is_file (). then_some ( p); 154} 155colrv1_font_present ( dirs) ?; 156ensure_config ( dir, system_config) 157} 158 159# [ cfg ( test )] 160mod tests{ 161use super :: * ; 162 163fn env_from ( pairs : & [( & str , & str )]) ->impl Fn ( & str ) ->Option < String > { 164let owned: Vec <( String , String )> = pairs. iter (). map ( |( k, v) |( k. to_string (), v. to_string ())). collect (); 165move |k : & str | owned. iter (). find ( |( a, _) | a == k). map ( |( _, v) | v. clone ()) 166} 167 168fn scratch ( name : & str ) ->PathBuf { 169let dir = std:: env:: temp_dir (). join ( format! ( "strata-fontguard-{name}-{}" , std:: process:: id ())); 170let _ = std:: fs:: remove_dir_all ( & dir); 171 std:: fs:: create_dir_all ( & dir). unwrap (); 172 dir 173} 174 175# [ test ] 176fn the_file_includes_the_system_config_first_and_rejects_only_colrv1_faces_inside_selectfont () { 177let text =config_text ( "/etc/fonts/fonts.conf" ); 178assert! ( text. starts_with ( "<?xml" )); 179let include = text. find ( "/etc/fonts/fonts.conf" ). expect ( "the system's fonts are kept" ); 180let select = text. find ( "<selectfont>" ). expect ( "a rejection needs <selectfont>" ); 181let select_end = text. find ( "</selectfont>" ). expect ( "closed" ); 182assert! ( include < select && select < select_end); 183assert_eq! ( text. matches ( "<rejectfont>" ). count (), COLRV1_GLOBS . len ()); 184for globin COLRV1_GLOBS { 185let at = text. find ( & format! ( "<glob>{glob}</glob>" )). unwrap_or_else ( ||panic! ( "{glob} is rejected" )); 186assert! ( at > select && at < select_end, "{glob} is inside <selectfont>" ); 187} 188// the bitmap and the outline faces stay 189assert! ( !text. contains ( "NotoColorEmoji.ttf" ) && !text. contains ( "NotoEmoji-Regular.ttf" )); 190assert! ( text. contains ( "<prefer><family>Noto Emoji</family></prefer>" )); 191assert! ( !text. contains ( '{' ) && !text. contains ( '}' ), "no placeholder left: {text}" ); 192// well formed enough: every opened tag is closed 193for tagin [ "fontconfig" , "selectfont" , "alias" ] { 194assert_eq! ( text. matches ( & format! ( "<{tag}" )). count (), text. matches ( & format! ( "</{tag}>" )). count (), "{tag}" ); 195} 196} 197 198# [ test ] 199fn 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 201let hit = |name : & str |COLRV1_GLOBS . iter (). any ( |g|{ let core = g. trim_matches ( '*' ); name. contains ( core) }); 202for badin [ "/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" ] { 204assert! ( hit ( bad), "{bad}" ); 205} 206for goodin [ "/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" ] { 209assert! ( !hit ( good), "{good}" ); 210} 211} 212 213# [ test ] 214fn a_persons_own_fontconfig_or_an_opt_out_leaves_the_environment_alone () { 215let dir =scratch ( "own" ); 216let system = dir. join ( "system.conf" ); 217 std:: fs:: write ( & system, b"<fontconfig/>" ). unwrap (); 218let fonts = dir. join ( "fonts" ); 219 std:: fs:: create_dir_all ( & fonts). unwrap (); 220 std:: fs:: write ( fonts. join ( "Noto-COLRv1.ttf" ), b"x" ). unwrap (); 221let dirs =vec! [ fonts]; 222assert_eq! ( config_for ( & env_from ( & [( "FONTCONFIG_FILE" , "/home/me/fonts.conf" )]), & dir, & dirs, & system), None ); 223assert_eq! ( config_for ( & env_from ( & [( "STRATA_FONT_CONFIG" , "off" )]), & dir, & dirs, & system), None ); 224let theirs = dir. join ( "theirs.conf" ); 225 std:: fs:: write ( & theirs, b"<fontconfig/>" ). unwrap (); 226assert_eq! ( config_for ( & env_from ( & [( "STRATA_FONT_CONFIG" , theirs. to_str (). unwrap ())]), & dir, & dirs, & system), Some ( theirs)); 227assert_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 229assert! ( config_for ( & env_from ( & []), & dir. join ( "out" ), & dirs, & system). is_some ()); 230let _ = std:: fs:: remove_dir_all ( & dir); 231} 232 233# [ test ] 234fn a_machine_without_a_colrv1_font_is_not_touched () { 235let dir =scratch ( "none" ); 236let system = dir. join ( "system.conf" ); 237 std:: fs:: write ( & system, b"<fontconfig/>" ). unwrap (); 238let 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 (); 243assert_eq! ( colrv1_font_present ( & [ fonts. clone ()]), None ); 244assert_eq! ( config_for ( & env_from ( & []), & dir. join ( "out" ), & [ fonts. clone ()], & system), None ); 245assert! ( !dir. join ( "out" ). exists (), "nothing is written" ); 246 std:: fs:: write ( fonts. join ( "noto/Noto-COLRv1.ttf" ), b"colour" ). unwrap (); 247assert! ( colrv1_font_present ( & [ fonts]). is_some ()); 248let _ = std:: fs:: remove_dir_all ( & dir); 249} 250 251# [ test ] 252fn the_scan_is_shallow_and_a_missing_folder_is_fine () { 253let dir =scratch ( "deep" ); 254let mut deep = dir. clone (); 255for iin 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 (); 258assert_eq! ( colrv1_font_present ( & [ dir. clone (), dir. join ( "missing" )]), None , "nine levels down is not a font folder" ); 259let _ = std:: fs:: remove_dir_all ( & dir); 260} 261 262# [ test ] 263fn the_folders_follow_the_xdg_variables () { 264let none =font_dirs ( & env_from ( & [( "HOME" , "/home/me" )])); 265assert! ( none. contains ( & PathBuf :: from ( "/usr/share/fonts" ))); 266assert! ( none. contains ( & PathBuf :: from ( "/home/me/.local/share/fonts" ))); 267assert! ( none. contains ( & PathBuf :: from ( "/home/me/.fonts" ))); 268let set =font_dirs ( & env_from ( & [( "HOME" , "/home/me" ), ( "XDG_DATA_HOME" , "/data/me" ), ( "XDG_DATA_DIRS" , "/usr/local/share:/var/lib/flatpak/exports/share" )])); 269assert! ( set. contains ( & PathBuf :: from ( "/data/me/fonts" ))); 270assert! ( !set. contains ( & PathBuf :: from ( "/home/me/.local/share/fonts" ))); 271assert! ( set. contains ( & PathBuf :: from ( "/var/lib/flatpak/exports/share/fonts" ))); 272} 273 274# [ test ] 275fn the_file_is_written_once_an_old_one_is_put_right_and_nothing_is_left_behind () { 276let dir =scratch ( "write" ); 277let system = dir. join ( "system.conf" ); 278 std:: fs:: write ( & system, b"<fontconfig/>" ). unwrap (); 279let out = dir. join ( "out" ); 280let first =ensure_config ( & out, & system). expect ( "written" ); 281assert_eq! ( ensure_config ( & out, & system). unwrap (), first, "the same path every start" ); 282 std:: fs:: write ( & first, "<fontconfig/>" ). unwrap (); 283assert_eq! ( ensure_config ( & out, & system), Some ( first. clone ())); 284assert_eq! ( std:: fs:: read_to_string ( & first). unwrap (), config_text ( & system. to_string_lossy ())); 285assert_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) 287assert_eq! ( ensure_config ( & dir. join ( "out2" ), & dir. join ( "absent.conf" )), None ); 288assert! ( !dir. join ( "out2" ). exists ()); 289let _ = std:: fs:: remove_dir_all ( & dir); 290} 291}