| ... | @@ -36,19 +36,15 @@ impl Font { | ... | @@ -36,19 +36,15 @@ impl Font { |
| 36 | pub fn find(family: &str, style: &str) -> Option<Arc<Font>> { | 36 | pub fn find(family: &str, style: &str) -> Option<Arc<Font>> { |
| 37 | { | 37 | { |
| 38 | let cache = font_cache().lock().unwrap(); | 38 | let cache = font_cache().lock().unwrap(); |
| 39 | if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) { | 39 | if let Some(hit) = cache.1.get(&(family.to_owned(), style.to_owned())) { |
| 40 | return hit.clone(); | 40 | return hit.clone(); |
| 41 | } | 41 | } |
| 42 | } | 42 | } |
| 43 | let resolved = { | 43 | let (resolved, resolved_gen) = { |
| 44 | let mut reg = registry().write().unwrap(); | 44 | let mut reg = registry().write().unwrap(); |
| 45 | resolve_lazy(&mut reg, family, style).map(Arc::new) | 45 | (resolve_lazy(&mut reg, family, style).map(Arc::new), reg.generation) |
| 46 | }; | 46 | }; |
| 47 | let mut cache = font_cache().lock().unwrap(); | 47 | cache_resolved_font(family, style, resolved, resolved_gen) |
| 48 | let entry = cache | | |
| 49 | .entry((family.to_owned(), style.to_owned())) | | |
| 50 | .or_insert_with(|| resolved.clone()); | | |
| 51 | entry.clone() | | |
| 52 | } | 48 | } |
| 53 | | 49 | |
| 54 | pub fn face(&self) -> Face<'_> { | 50 | pub fn face(&self) -> Face<'_> { |
| ... | @@ -63,6 +59,7 @@ impl Font { | ... | @@ -63,6 +59,7 @@ impl Font { |
| 63 | struct FontRegistry { | 59 | struct FontRegistry { |
| 64 | db: fontdb::Database, | 60 | db: fontdb::Database, |
| 65 | aliases: HashMap<String, Vec<fontdb::ID>>, | 61 | aliases: HashMap<String, Vec<fontdb::ID>>, |
| | 62 | generation: u64, |
| 66 | #[cfg(not(target_arch = "wasm32"))] | 63 | #[cfg(not(target_arch = "wasm32"))] |
| 67 | system_fonts_loaded: bool, | 64 | system_fonts_loaded: bool, |
| 68 | #[cfg(not(target_arch = "wasm32"))] | 65 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -78,6 +75,7 @@ impl FontRegistry { | ... | @@ -78,6 +75,7 @@ impl FontRegistry { |
| 78 | Self { | 75 | Self { |
| 79 | db: fontdb::Database::new(), | 76 | db: fontdb::Database::new(), |
| 80 | aliases: HashMap::new(), | 77 | aliases: HashMap::new(), |
| | 78 | generation: 0, |
| 81 | #[cfg(not(target_arch = "wasm32"))] | 79 | #[cfg(not(target_arch = "wasm32"))] |
| 82 | system_fonts_loaded: false, | 80 | system_fonts_loaded: false, |
| 83 | #[cfg(not(target_arch = "wasm32"))] | 81 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -98,11 +96,35 @@ impl FontRegistry { | ... | @@ -98,11 +96,35 @@ impl FontRegistry { |
| 98 | } | 96 | } |
| 99 | } | 97 | } |
| 100 | | 98 | |
| 101 | fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> { | 99 | type FontCacheMap = HashMap<(String, String), Option<Arc<Font>>>; |
| 102 | static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new(); | 100 | |
| | 101 | fn font_cache() -> &'static Mutex<(u64, FontCacheMap)> { |
| | 102 | static CACHE: OnceLock<Mutex<(u64, FontCacheMap)>> = OnceLock::new(); |
| 103 | CACHE.get_or_init(Default::default) | 103 | CACHE.get_or_init(Default::default) |
| 104 | } | 104 | } |
| 105 | | 105 | |
| | 106 | fn cache_resolved_font( |
| | 107 | family: &str, |
| | 108 | style: &str, |
| | 109 | resolved: Option<Arc<Font>>, |
| | 110 | resolved_gen: u64, |
| | 111 | ) -> Option<Arc<Font>> { |
| | 112 | let mut cache = font_cache().lock().unwrap(); |
| | 113 | if cache.0 != resolved_gen { |
| | 114 | if cache.0 < resolved_gen { |
| | 115 | cache.0 = resolved_gen; |
| | 116 | cache.1.clear(); |
| | 117 | } else { |
| | 118 | return resolved; |
| | 119 | } |
| | 120 | } |
| | 121 | let entry = cache |
| | 122 | .1 |
| | 123 | .entry((family.to_owned(), style.to_owned())) |
| | 124 | .or_insert_with(|| resolved.clone()); |
| | 125 | entry.clone() |
| | 126 | } |
| | 127 | |
| 106 | fn registry() -> &'static RwLock<FontRegistry> { | 128 | fn registry() -> &'static RwLock<FontRegistry> { |
| 107 | static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new(); | 129 | static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new(); |
| 108 | REG.get_or_init(|| RwLock::new(FontRegistry::new())) | 130 | REG.get_or_init(|| RwLock::new(FontRegistry::new())) |
| ... | @@ -207,6 +229,8 @@ fn is_style_suffix(rest: &str) -> bool { | ... | @@ -207,6 +229,8 @@ fn is_style_suffix(rest: &str) -> bool { |
| 207 | "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy", | 229 | "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy", |
| 208 | "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow", | 230 | "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow", |
| 209 | "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps", | 231 | "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps", |
| | 232 | "b", "i", "z", "l", "sl", "sb", "cond", "display", "text", |
| | 233 | "100", "200", "300", "400", "500", "600", "700", "800", "900", |
| 210 | ]; | 234 | ]; |
| 211 | rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p)) | 235 | rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p)) |
| 212 | } | 236 | } |
| ... | @@ -249,17 +273,23 @@ fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) { | ... | @@ -249,17 +273,23 @@ fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) { |
| 249 | /// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime | 273 | /// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime |
| 250 | /// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache. | 274 | /// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache. |
| 251 | pub fn register_font_bytes(bytes: Vec<u8>) { | 275 | pub fn register_font_bytes(bytes: Vec<u8>) { |
| 252 | { | 276 | let new_gen = { |
| 253 | let mut reg = registry().write().unwrap(); | 277 | let mut reg = registry().write().unwrap(); |
| 254 | reg.db.load_font_data(bytes); | 278 | reg.db.load_font_data(bytes); |
| | 279 | reg.generation += 1; |
| | 280 | reg.generation |
| | 281 | }; |
| | 282 | let mut cache = font_cache().lock().unwrap(); |
| | 283 | if cache.0 < new_gen { |
| | 284 | cache.0 = new_gen; |
| | 285 | cache.1.clear(); |
| 255 | } | 286 | } |
| 256 | font_cache().lock().unwrap().clear(); | | |
| 257 | } | 287 | } |
| 258 | | 288 | |
| 259 | /// Registers font bytes under an explicit family alias in addition to its embedded family names, | 289 | /// Registers font bytes under an explicit family alias in addition to its embedded family names, |
| 260 | /// and clears the resolution cache. | 290 | /// and clears the resolution cache. |
| 261 | pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { | 291 | pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { |
| 262 | { | 292 | let new_gen = { |
| 263 | let mut reg = registry().write().unwrap(); | 293 | let mut reg = registry().write().unwrap(); |
| 264 | let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect(); | 294 | let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect(); |
| 265 | reg.db.load_font_data(bytes); | 295 | reg.db.load_font_data(bytes); |
| ... | @@ -272,8 +302,14 @@ pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { | ... | @@ -272,8 +302,14 @@ pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { |
| 272 | .extend(added); | 302 | .extend(added); |
| 273 | } | 303 | } |
| 274 | } | 304 | } |
| | 305 | reg.generation += 1; |
| | 306 | reg.generation |
| | 307 | }; |
| | 308 | let mut cache = font_cache().lock().unwrap(); |
| | 309 | if cache.0 < new_gen { |
| | 310 | cache.0 = new_gen; |
| | 311 | cache.1.clear(); |
| 275 | } | 312 | } |
| 276 | font_cache().lock().unwrap().clear(); | | |
| 277 | } | 313 | } |
| 278 | | 314 | |
| 279 | /// CSS-style weight and italic flag for a Fusion style name. | 315 | /// CSS-style weight and italic flag for a Fusion style name. |
| ... | @@ -375,7 +411,15 @@ fn try_pick_family_lazy( | ... | @@ -375,7 +411,15 @@ fn try_pick_family_lazy( |
| 375 | load_family_candidates(reg, &fam_norm); | 411 | load_family_candidates(reg, &fam_norm); |
| 376 | } | 412 | } |
| 377 | } | 413 | } |
| 378 | pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) | 414 | let picked = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic); |
| | 415 | #[cfg(not(target_arch = "wasm32"))] |
| | 416 | if let Some(id) = picked { |
| | 417 | if !reg.system_fonts_loaded && !is_exact_face_match(&reg.db, id, wanted_style, weight, italic) { |
| | 418 | reg.ensure_system_fonts_loaded(); |
| | 419 | return pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic); |
| | 420 | } |
| | 421 | } |
| | 422 | picked |
| 379 | } | 423 | } |
| 380 | | 424 | |
| 381 | fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> { | 425 | fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> { |
| ... | @@ -386,7 +430,13 @@ fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Fon | ... | @@ -386,7 +430,13 @@ fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Fon |
| 386 | .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic))); | 430 | .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic))); |
| 387 | | 431 | |
| 388 | #[cfg(not(target_arch = "wasm32"))] | 432 | #[cfg(not(target_arch = "wasm32"))] |
| 389 | if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded { | 433 | if !family.is_empty() |
| | 434 | && !reg.system_fonts_loaded |
| | 435 | && match id { |
| | 436 | None => true, |
| | 437 | Some(found) => !is_exact_face_match(&reg.db, found, &wanted, weight, italic), |
| | 438 | } |
| | 439 | { |
| 390 | reg.ensure_system_fonts_loaded(); | 440 | reg.ensure_system_fonts_loaded(); |
| 391 | id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic) | 441 | id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic) |
| 392 | .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic))); | 442 | .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic))); |
| ... | @@ -941,6 +991,7 @@ const GLYPH_BASELINE_ANCHOR: f32 = 256.0; | ... | @@ -941,6 +991,7 @@ const GLYPH_BASELINE_ANCHOR: f32 = 256.0; |
| 941 | const GLYPH_BASELINE_ANCHOR_I32: i32 = 256; | 991 | const GLYPH_BASELINE_ANCHOR_I32: i32 = 256; |
| 942 | const MAX_GLYPH_CACHE_ENTRIES: usize = 4096; | 992 | const MAX_GLYPH_CACHE_ENTRIES: usize = 4096; |
| 943 | const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024; | 993 | const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024; |
| | 994 | const MAX_GLYPH_COORD: f32 = 8_388_608.0; |
| 944 | | 995 | |
| 945 | #[derive(Clone, Copy, PartialEq, Eq, Hash)] | 996 | #[derive(Clone, Copy, PartialEq, Eq, Hash)] |
| 946 | struct GlyphCacheKey { | 997 | struct GlyphCacheKey { |
| ... | @@ -960,8 +1011,9 @@ struct CachedGlyphCoverage { | ... | @@ -960,8 +1011,9 @@ struct CachedGlyphCoverage { |
| 960 | } | 1011 | } |
| 961 | | 1012 | |
| 962 | struct GlyphCache { | 1013 | struct GlyphCache { |
| 963 | map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>, | 1014 | map: HashMap<GlyphCacheKey, (u64, Arc<CachedGlyphCoverage>)>, |
| 964 | order: VecDeque<GlyphCacheKey>, | 1015 | order: VecDeque<(u64, GlyphCacheKey)>, |
| | 1016 | next_stamp: u64, |
| 965 | total_bytes: usize, | 1017 | total_bytes: usize, |
| 966 | } | 1018 | } |
| 967 | | 1019 | |
| ... | @@ -970,29 +1022,58 @@ impl GlyphCache { | ... | @@ -970,29 +1022,58 @@ impl GlyphCache { |
| 970 | Self { | 1022 | Self { |
| 971 | map: HashMap::new(), | 1023 | map: HashMap::new(), |
| 972 | order: VecDeque::new(), | 1024 | order: VecDeque::new(), |
| | 1025 | next_stamp: 0, |
| 973 | total_bytes: 0, | 1026 | total_bytes: 0, |
| 974 | } | 1027 | } |
| 975 | } | 1028 | } |
| 976 | | 1029 | |
| 977 | fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> { | 1030 | fn compact_order(&mut self) { |
| 978 | self.map.get(key).cloned() | 1031 | let mut live: Vec<(u64, GlyphCacheKey)> = |
| | 1032 | self.map.iter().map(|(k, (s, _))| (*s, *k)).collect(); |
| | 1033 | live.sort_unstable_by_key(|&(s, _)| s); |
| | 1034 | self.order.clear(); |
| | 1035 | self.order.extend(live); |
| | 1036 | } |
| | 1037 | |
| | 1038 | fn get(&mut self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> { |
| | 1039 | let (stamp, val) = self.map.get_mut(key)?; |
| | 1040 | self.next_stamp += 1; |
| | 1041 | *stamp = self.next_stamp; |
| | 1042 | self.order.push_back((self.next_stamp, *key)); |
| | 1043 | let out = Arc::clone(val); |
| | 1044 | if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 { |
| | 1045 | self.compact_order(); |
| | 1046 | } |
| | 1047 | Some(out) |
| 979 | } | 1048 | } |
| 980 | | 1049 | |
| 981 | fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) { | 1050 | fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) { |
| 982 | if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) { | 1051 | if val.bytes > MAX_GLYPH_CACHE_BYTES { |
| | 1052 | return; |
| | 1053 | } |
| | 1054 | if let Some((stamp, _)) = self.map.get_mut(&key) { |
| | 1055 | self.next_stamp += 1; |
| | 1056 | *stamp = self.next_stamp; |
| | 1057 | self.order.push_back((self.next_stamp, key)); |
| | 1058 | if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 { |
| | 1059 | self.compact_order(); |
| | 1060 | } |
| 983 | return; | 1061 | return; |
| 984 | } | 1062 | } |
| 985 | while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES { | 1063 | while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES { |
| 986 | let Some(old_key) = self.order.pop_front() else { | 1064 | let Some((s, old_key)) = self.order.pop_front() else { |
| 987 | break; | 1065 | break; |
| 988 | }; | 1066 | }; |
| 989 | if let Some(removed) = self.map.remove(&old_key) { | 1067 | if self.map.get(&old_key).is_some_and(|(cur_s, _)| *cur_s == s) { |
| 990 | self.total_bytes = self.total_bytes.saturating_sub(removed.bytes); | 1068 | if let Some((_, removed)) = self.map.remove(&old_key) { |
| | 1069 | self.total_bytes = self.total_bytes.saturating_sub(removed.bytes); |
| | 1070 | } |
| 991 | } | 1071 | } |
| 992 | } | 1072 | } |
| | 1073 | self.next_stamp += 1; |
| 993 | self.total_bytes += val.bytes; | 1074 | self.total_bytes += val.bytes; |
| 994 | self.order.push_back(key); | 1075 | self.order.push_back((self.next_stamp, key)); |
| 995 | self.map.insert(key, val); | 1076 | self.map.insert(key, (self.next_stamp, val)); |
| 996 | } | 1077 | } |
| 997 | } | 1078 | } |
| 998 | | 1079 | |
| ... | @@ -1001,11 +1082,32 @@ fn glyph_cache() -> &'static Mutex<GlyphCache> { | ... | @@ -1001,11 +1082,32 @@ fn glyph_cache() -> &'static Mutex<GlyphCache> { |
| 1001 | CACHE.get_or_init(|| Mutex::new(GlyphCache::new())) | 1082 | CACHE.get_or_init(|| Mutex::new(GlyphCache::new())) |
| 1002 | } | 1083 | } |
| 1003 | | 1084 | |
| | 1085 | fn quantize_subpixel(coord: f32) -> Option<(i32, f32)> { |
| | 1086 | if !coord.is_finite() || coord.abs() > MAX_GLYPH_COORD { |
| | 1087 | return None; |
| | 1088 | } |
| | 1089 | let mut ix = coord.floor() as i32; |
| | 1090 | let fx = (coord - ix as f32).clamp(0.0, 1.0); |
| | 1091 | let mut qx = (fx * 16.0).round() as i32; |
| | 1092 | if qx >= 16 { |
| | 1093 | ix += 1; |
| | 1094 | qx = 0; |
| | 1095 | } |
| | 1096 | Some((ix, qx as f32 * (1.0 / 16.0))) |
| | 1097 | } |
| | 1098 | |
| 1004 | fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) { | 1099 | fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) { |
| 1005 | let ix = spec.abs_x.floor() as i32; | 1100 | let (Some((ix, fx)), Some((iy, fy))) = (quantize_subpixel(spec.abs_x), quantize_subpixel(spec.abs_y)) else { |
| 1006 | let iy = spec.abs_y.floor() as i32; | 1101 | return ( |
| 1007 | let fx = spec.abs_x - ix as f32; | 1102 | 0, |
| 1008 | let fy = spec.abs_y - iy as f32; | 1103 | 0, |
| | 1104 | Arc::new(CachedGlyphCoverage { |
| | 1105 | fill: None, |
| | 1106 | stroke: None, |
| | 1107 | bytes: 0, |
| | 1108 | }), |
| | 1109 | ); |
| | 1110 | }; |
| 1009 | | 1111 | |
| 1010 | let total_lean = spec.font.lean + spec.shear; | 1112 | let total_lean = spec.font.lean + spec.shear; |
| 1011 | let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean }; | 1113 | let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean }; |
| ... | @@ -1245,8 +1347,8 @@ pub fn rasterize_text_plus_rich( | ... | @@ -1245,8 +1347,8 @@ pub fn rasterize_text_plus_rich( |
| 1245 | let top = c.top.saturating_add(oy); | 1347 | let top = c.top.saturating_add(oy); |
| 1246 | min_x = min_x.min(left.saturating_sub(pad)); | 1348 | min_x = min_x.min(left.saturating_sub(pad)); |
| 1247 | min_y = min_y.min(top.saturating_sub(pad)); | 1349 | min_y = min_y.min(top.saturating_sub(pad)); |
| 1248 | max_x = max_x.max((left + c.width as i32).saturating_add(pad)); | 1350 | max_x = max_x.max(left.saturating_add(c.width as i32).saturating_add(pad)); |
| 1249 | max_y = max_y.max((top + c.height as i32).saturating_add(pad)); | 1351 | max_y = max_y.max(top.saturating_add(c.height as i32).saturating_add(pad)); |
| 1250 | }; | 1352 | }; |
| 1251 | | 1353 | |
| 1252 | let mut placed = Vec::with_capacity(specs.len()); | 1354 | let mut placed = Vec::with_capacity(specs.len()); |
| ... | @@ -2353,7 +2455,8 @@ mod tests { | ... | @@ -2353,7 +2455,8 @@ mod tests { |
| 2353 | let tight_canvas = composite_onto_canvas(tsz, torig, &trgba); | 2455 | let tight_canvas = composite_onto_canvas(tsz, torig, &trgba); |
| 2354 | let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba); | 2456 | let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba); |
| 2355 | for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() { | 2457 | for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() { |
| 2356 | assert!(a.abs_diff(b) <= 4, "legacy parity diff at byte {i}: {a} vs {b}"); | 2458 | // 1/16 px subpixel quantization in `cached_glyph_coverage` can shift x/y by <= 1/32 px each (~16 u8 levels). |
| | 2459 | assert!(a.abs_diff(b) <= 16, "legacy parity diff at byte {i}: {a} vs {b}"); |
| 2357 | } | 2460 | } |
| 2358 | let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80); | 2461 | let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80); |
| 2359 | assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain)); | 2462 | assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain)); |
| ... | @@ -2515,4 +2618,140 @@ mod tests { | ... | @@ -2515,4 +2618,140 @@ mod tests { |
| 2515 | } | 2618 | } |
| 2516 | assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}"); | 2619 | assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}"); |
| 2517 | } | 2620 | } |
| | 2621 | |
| | 2622 | #[test] |
| | 2623 | fn glyph_cache_subpixel_quantization_and_lru_eviction() { |
| | 2624 | assert_eq!(quantize_subpixel(10.99), Some((11, 0.0))); |
| | 2625 | assert_eq!(quantize_subpixel(-0.01), Some((0, 0.0))); |
| | 2626 | assert_eq!(quantize_subpixel(10.01), quantize_subpixel(10.02)); |
| | 2627 | |
| | 2628 | let font = Font::find("Helvetica", "Regular").expect("system font"); |
| | 2629 | let gid = font.face().glyph_index('A').expect("glyph A"); |
| | 2630 | let make_spec = |x: f32, y: f32| GlyphSpec { |
| | 2631 | font: Arc::clone(&font), |
| | 2632 | glyph_id: gid, |
| | 2633 | font_px: 42.0, |
| | 2634 | abs_x: x, |
| | 2635 | abs_y: y, |
| | 2636 | shear: 0.0, |
| | 2637 | outline_w: 0.0, |
| | 2638 | }; |
| | 2639 | let (ix1, iy1, cov1) = cached_glyph_coverage(&make_spec(100.01, 200.01), false); |
| | 2640 | let (ix2, iy2, cov2) = cached_glyph_coverage(&make_spec(100.02, 200.02), false); |
| | 2641 | assert_eq!((ix1, iy1), (100, 200)); |
| | 2642 | assert_eq!((ix2, iy2), (100, 200)); |
| | 2643 | assert!(Arc::ptr_eq(&cov1, &cov2), "jitter within 1/16 px must share cached coverage"); |
| | 2644 | |
| | 2645 | // Verify LRU eviction (touching key 0 keeps it alive when capacity is exceeded). |
| | 2646 | let mut cache = GlyphCache::new(); |
| | 2647 | let make_key = |i: u16| GlyphCacheKey { |
| | 2648 | font_id: 777, |
| | 2649 | glyph_id: i, |
| | 2650 | size_bits: 42.0_f32.to_bits(), |
| | 2651 | lean_bits: 0, |
| | 2652 | stroke_bits: 0, |
| | 2653 | sub_x_bits: 0, |
| | 2654 | sub_y_bits: 0, |
| | 2655 | }; |
| | 2656 | let make_entry = || { |
| | 2657 | Arc::new(CachedGlyphCoverage { |
| | 2658 | fill: Some(Coverage { |
| | 2659 | left: 0, |
| | 2660 | top: 0, |
| | 2661 | width: 4, |
| | 2662 | height: 4, |
| | 2663 | data: vec![255; 16], |
| | 2664 | }), |
| | 2665 | stroke: None, |
| | 2666 | bytes: 16, |
| | 2667 | }) |
| | 2668 | }; |
| | 2669 | for i in 0..MAX_GLYPH_CACHE_ENTRIES { |
| | 2670 | cache.insert(make_key(i as u16), make_entry()); |
| | 2671 | } |
| | 2672 | // Touch key 0 so key 1 becomes the least recently used entry. |
| | 2673 | assert!(cache.get(&make_key(0)).is_some()); |
| | 2674 | cache.insert(make_key(MAX_GLYPH_CACHE_ENTRIES as u16), make_entry()); |
| | 2675 | assert!(cache.get(&make_key(0)).is_some(), "recently touched entry must survive LRU eviction"); |
| | 2676 | assert!(cache.get(&make_key(1)).is_none(), "least recently used entry must be evicted"); |
| | 2677 | } |
| | 2678 | |
| | 2679 | #[test] |
| | 2680 | fn register_font_bytes_generation_prevents_stale_cache_poisoning() { |
| | 2681 | let base = Font::find("Helvetica", "Regular").expect("system fallback font"); |
| | 2682 | let gen0 = registry().read().unwrap().generation; |
| | 2683 | register_font_bytes_with_name("FissionGenRaceFont", base.data.clone()); |
| | 2684 | let gen1 = registry().read().unwrap().generation; |
| | 2685 | assert!(gen1 > gen0); |
| | 2686 | |
| | 2687 | // Simulate a thread that finished resolve_lazy at gen0 before register_font_bytes_with_name ran. |
| | 2688 | let _ = cache_resolved_font("FissionGenRaceFont", "Regular", None, gen0); |
| | 2689 | { |
| | 2690 | let cache = font_cache().lock().unwrap(); |
| | 2691 | assert_eq!(cache.0, gen1); |
| | 2692 | assert!( |
| | 2693 | !cache.1.contains_key(&("FissionGenRaceFont".to_owned(), "Regular".to_owned())), |
| | 2694 | "stale pre-registration result must not poison font_cache" |
| | 2695 | ); |
| | 2696 | } |
| | 2697 | assert!(Font::find("FissionGenRaceFont", "Regular").is_some()); |
| | 2698 | } |
| | 2699 | |
| | 2700 | #[test] |
| | 2701 | fn extreme_off_canvas_coords_never_overflow_i32() { |
| | 2702 | for bad in [ |
| | 2703 | f32::NAN, |
| | 2704 | f32::INFINITY, |
| | 2705 | f32::NEG_INFINITY, |
| | 2706 | f32::MAX, |
| | 2707 | f32::MIN, |
| | 2708 | 1e15, |
| | 2709 | -1e15, |
| | 2710 | (i32::MAX as f32) * 2.0, |
| | 2711 | (i32::MIN as f32) * 2.0, |
| | 2712 | ] { |
| | 2713 | assert_eq!(quantize_subpixel(bad), None); |
| | 2714 | } |
| | 2715 | |
| | 2716 | let font = Font::find("Helvetica", "Regular").expect("system font"); |
| | 2717 | let gid = font.face().glyph_index('A').expect("glyph A"); |
| | 2718 | for (ax, ay) in [(1e20_f32, 0.0_f32), (0.0, -1e20), (f32::NAN, 10.0), (f32::INFINITY, f32::NEG_INFINITY)] { |
| | 2719 | let spec = GlyphSpec { |
| | 2720 | font: Arc::clone(&font), |
| | 2721 | glyph_id: gid, |
| | 2722 | font_px: 32.0, |
| | 2723 | abs_x: ax, |
| | 2724 | abs_y: ay, |
| | 2725 | shear: 0.0, |
| | 2726 | outline_w: 0.0, |
| | 2727 | }; |
| | 2728 | let (ix, iy, cov) = cached_glyph_coverage(&spec, false); |
| | 2729 | assert_eq!((ix, iy), (0, 0)); |
| | 2730 | assert!(cov.fill.is_none() && cov.stroke.is_none()); |
| | 2731 | } |
| | 2732 | |
| | 2733 | let p = RichTextPlusParams { |
| | 2734 | text: "Far", |
| | 2735 | font_family: "Helvetica", |
| | 2736 | font_style: "Regular", |
| | 2737 | size_norm: 0.08, |
| | 2738 | tracking: 1.0, |
| | 2739 | line_spacing: 1.0, |
| | 2740 | center: [1e12, -1e12], |
| | 2741 | h_lcr: 0.0, |
| | 2742 | v_tcb: 0.0, |
| | 2743 | fill_rgba: [1.0; 4], |
| | 2744 | write_on_start: 0.0, |
| | 2745 | write_on_end: 1.0, |
| | 2746 | shear_x: 0.0, |
| | 2747 | cls: &[], |
| | 2748 | outline_rgba: [0.0; 4], |
| | 2749 | outline_thickness_norm: 0.0, |
| | 2750 | outline_enabled: false, |
| | 2751 | soft_fill: [0.0; 3], |
| | 2752 | soft_outline: [0.0; 3], |
| | 2753 | baseline_at_center: false, |
| | 2754 | }; |
| | 2755 | assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0])); |
| | 2756 | } |
| 2518 | } | 2757 | } |