| ... | @@ -4,7 +4,10 @@ | ... | @@ -4,7 +4,10 @@ |
| 4 | | 4 | |
| 5 | use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag}; | 5 | use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag}; |
| 6 | use rustybuzz::{Face, Feature, UnicodeBuffer, Variation}; | 6 | use rustybuzz::{Face, Feature, UnicodeBuffer, Variation}; |
| 7 | use std::collections::{HashMap, HashSet}; | 7 | use std::collections::{HashMap, HashSet, VecDeque}; |
| | 8 | #[cfg(not(target_arch = "wasm32"))] |
| | 9 | use std::path::PathBuf; |
| | 10 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 8 | use std::sync::{Arc, Mutex, OnceLock, RwLock}; | 11 | use std::sync::{Arc, Mutex, OnceLock, RwLock}; |
| 9 | use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector}; | 12 | use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector}; |
| 10 | | 13 | |
| ... | @@ -15,8 +18,11 @@ const FALLBACK_FAMILIES: [&str; 6] = | ... | @@ -15,8 +18,11 @@ const FALLBACK_FAMILIES: [&str; 6] = |
| 15 | /// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face. | 18 | /// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face. |
| 16 | const SYNTHETIC_ITALIC: f32 = 0.2126; | 19 | const SYNTHETIC_ITALIC: f32 = 0.2126; |
| 17 | | 20 | |
| | 21 | static NEXT_FONT_ID: AtomicU64 = AtomicU64::new(1); |
| | 22 | |
| 18 | /// A resolved font file; `face()` parses it on demand. | 23 | /// A resolved font file; `face()` parses it on demand. |
| 19 | pub struct Font { | 24 | pub struct Font { |
| | 25 | id: u64, |
| 20 | data: Vec<u8>, | 26 | data: Vec<u8>, |
| 21 | index: u32, | 27 | index: u32, |
| 22 | weight: u16, | 28 | weight: u16, |
| ... | @@ -28,15 +34,21 @@ impl Font { | ... | @@ -28,15 +34,21 @@ impl Font { |
| 28 | /// system fonts and any fonts registered via [`register_font_bytes`], falling back through | 34 | /// system fonts and any fonts registered via [`register_font_bytes`], falling back through |
| 29 | /// [`FALLBACK_FAMILIES`] and finally any installed face. | 35 | /// [`FALLBACK_FAMILIES`] and finally any installed face. |
| 30 | pub fn find(family: &str, style: &str) -> Option<Arc<Font>> { | 36 | pub fn find(family: &str, style: &str) -> Option<Arc<Font>> { |
| | 37 | { |
| | 38 | let cache = font_cache().lock().unwrap(); |
| | 39 | if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) { |
| | 40 | return hit.clone(); |
| | 41 | } |
| | 42 | } |
| | 43 | let resolved = { |
| | 44 | let mut reg = registry().write().unwrap(); |
| | 45 | resolve_lazy(&mut reg, family, style).map(Arc::new) |
| | 46 | }; |
| 31 | let mut cache = font_cache().lock().unwrap(); | 47 | let mut cache = font_cache().lock().unwrap(); |
| 32 | cache | 48 | let entry = cache |
| 33 | .entry((family.to_owned(), style.to_owned())) | 49 | .entry((family.to_owned(), style.to_owned())) |
| 34 | .or_insert_with(|| { | 50 | .or_insert_with(|| resolved.clone()); |
| 35 | let db = database().read().unwrap(); | 51 | entry.clone() |
| 36 | let aliases = font_aliases().read().unwrap(); | | |
| 37 | resolve(&db, &aliases, family, style).map(Arc::new) | | |
| 38 | }) | | |
| 39 | .clone() | | |
| 40 | } | 52 | } |
| 41 | | 53 | |
| 42 | pub fn face(&self) -> Face<'_> { | 54 | pub fn face(&self) -> Face<'_> { |
| ... | @@ -48,33 +60,198 @@ impl Font { | ... | @@ -48,33 +60,198 @@ impl Font { |
| 48 | } | 60 | } |
| 49 | } | 61 | } |
| 50 | | 62 | |
| | 63 | struct FontRegistry { |
| | 64 | db: fontdb::Database, |
| | 65 | aliases: HashMap<String, Vec<fontdb::ID>>, |
| | 66 | #[cfg(not(target_arch = "wasm32"))] |
| | 67 | system_fonts_loaded: bool, |
| | 68 | #[cfg(not(target_arch = "wasm32"))] |
| | 69 | loaded_paths: HashSet<PathBuf>, |
| | 70 | #[cfg(not(target_arch = "wasm32"))] |
| | 71 | loaded_families: HashSet<String>, |
| | 72 | #[cfg(not(target_arch = "wasm32"))] |
| | 73 | loaded_style_keys: HashSet<(String, String)>, |
| | 74 | } |
| | 75 | |
| | 76 | impl FontRegistry { |
| | 77 | fn new() -> Self { |
| | 78 | Self { |
| | 79 | db: fontdb::Database::new(), |
| | 80 | aliases: HashMap::new(), |
| | 81 | #[cfg(not(target_arch = "wasm32"))] |
| | 82 | system_fonts_loaded: false, |
| | 83 | #[cfg(not(target_arch = "wasm32"))] |
| | 84 | loaded_paths: HashSet::new(), |
| | 85 | #[cfg(not(target_arch = "wasm32"))] |
| | 86 | loaded_families: HashSet::new(), |
| | 87 | #[cfg(not(target_arch = "wasm32"))] |
| | 88 | loaded_style_keys: HashSet::new(), |
| | 89 | } |
| | 90 | } |
| | 91 | |
| | 92 | #[cfg(not(target_arch = "wasm32"))] |
| | 93 | fn ensure_system_fonts_loaded(&mut self) { |
| | 94 | if !self.system_fonts_loaded { |
| | 95 | self.db.load_system_fonts(); |
| | 96 | self.system_fonts_loaded = true; |
| | 97 | } |
| | 98 | } |
| | 99 | } |
| | 100 | |
| 51 | fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> { | 101 | fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> { |
| 52 | static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new(); | 102 | static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new(); |
| 53 | CACHE.get_or_init(Default::default) | 103 | CACHE.get_or_init(Default::default) |
| 54 | } | 104 | } |
| 55 | | 105 | |
| 56 | fn font_aliases() -> &'static RwLock<HashMap<String, Vec<fontdb::ID>>> { | 106 | fn registry() -> &'static RwLock<FontRegistry> { |
| 57 | static ALIASES: OnceLock<RwLock<HashMap<String, Vec<fontdb::ID>>>> = OnceLock::new(); | 107 | static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new(); |
| 58 | ALIASES.get_or_init(Default::default) | 108 | REG.get_or_init(|| RwLock::new(FontRegistry::new())) |
| | 109 | } |
| | 110 | |
| | 111 | #[cfg(not(target_arch = "wasm32"))] |
| | 112 | struct FontFileEntry { |
| | 113 | path: PathBuf, |
| | 114 | stem_norm: String, |
| | 115 | } |
| | 116 | |
| | 117 | #[cfg(not(target_arch = "wasm32"))] |
| | 118 | fn norm_alnum(s: &str) -> String { |
| | 119 | s.chars() |
| | 120 | .filter(|c| c.is_ascii_alphanumeric()) |
| | 121 | .map(|c| c.to_ascii_lowercase()) |
| | 122 | .collect() |
| | 123 | } |
| | 124 | |
| | 125 | #[cfg(not(target_arch = "wasm32"))] |
| | 126 | fn is_font_extension(path: &std::path::Path) -> bool { |
| | 127 | path.extension() |
| | 128 | .and_then(|e| e.to_str()) |
| | 129 | .is_some_and(|ext| { |
| | 130 | ext.eq_ignore_ascii_case("ttf") |
| | 131 | || ext.eq_ignore_ascii_case("otf") |
| | 132 | || ext.eq_ignore_ascii_case("ttc") |
| | 133 | || ext.eq_ignore_ascii_case("otc") |
| | 134 | }) |
| 59 | } | 135 | } |
| 60 | | 136 | |
| 61 | fn database() -> &'static RwLock<fontdb::Database> { | 137 | #[cfg(not(target_arch = "wasm32"))] |
| 62 | static DB: OnceLock<RwLock<fontdb::Database>> = OnceLock::new(); | 138 | fn collect_font_dir(dir: &std::path::Path, depth: u8, out: &mut Vec<FontFileEntry>) { |
| 63 | DB.get_or_init(|| { | 139 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 64 | #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] | 140 | return; |
| 65 | let mut db = fontdb::Database::new(); | 141 | }; |
| 66 | #[cfg(not(target_arch = "wasm32"))] | 142 | for entry in entries.flatten() { |
| 67 | db.load_system_fonts(); | 143 | let path = entry.path(); |
| 68 | RwLock::new(db) | 144 | if path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) { |
| | 145 | continue; |
| | 146 | } |
| | 147 | let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) |
| | 148 | || (entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) && path.is_dir()); |
| | 149 | if is_dir { |
| | 150 | if depth > 0 { |
| | 151 | collect_font_dir(&path, depth - 1, out); |
| | 152 | } |
| | 153 | } else if is_font_extension(&path) { |
| | 154 | if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { |
| | 155 | let stem_norm = norm_alnum(stem); |
| | 156 | if !stem_norm.is_empty() { |
| | 157 | out.push(FontFileEntry { path, stem_norm }); |
| | 158 | } |
| | 159 | } |
| | 160 | } |
| | 161 | } |
| | 162 | } |
| | 163 | |
| | 164 | #[cfg(not(target_arch = "wasm32"))] |
| | 165 | fn system_font_index() -> &'static [FontFileEntry] { |
| | 166 | static INDEX: OnceLock<Vec<FontFileEntry>> = OnceLock::new(); |
| | 167 | INDEX.get_or_init(|| { |
| | 168 | let mut out = Vec::with_capacity(768); |
| | 169 | let mut dirs: Vec<PathBuf> = Vec::new(); |
| | 170 | #[cfg(target_os = "macos")] |
| | 171 | { |
| | 172 | dirs.push(PathBuf::from("/System/Library/Fonts")); |
| | 173 | dirs.push(PathBuf::from("/Library/Fonts")); |
| | 174 | if let Some(home) = std::env::var_os("HOME") { |
| | 175 | dirs.push(PathBuf::from(home).join("Library/Fonts")); |
| | 176 | } |
| | 177 | } |
| | 178 | #[cfg(all(unix, not(target_os = "macos")))] |
| | 179 | { |
| | 180 | dirs.push(PathBuf::from("/usr/share/fonts")); |
| | 181 | dirs.push(PathBuf::from("/usr/local/share/fonts")); |
| | 182 | if let Some(home) = std::env::var_os("HOME") { |
| | 183 | let h = PathBuf::from(home); |
| | 184 | dirs.push(h.join(".local/share/fonts")); |
| | 185 | dirs.push(h.join(".fonts")); |
| | 186 | } |
| | 187 | } |
| | 188 | #[cfg(target_os = "windows")] |
| | 189 | { |
| | 190 | if let Some(win) = std::env::var_os("WINDIR") { |
| | 191 | dirs.push(PathBuf::from(win).join("Fonts")); |
| | 192 | } |
| | 193 | if let Some(local) = std::env::var_os("LOCALAPPDATA") { |
| | 194 | dirs.push(PathBuf::from(local).join("Microsoft/Windows/Fonts")); |
| | 195 | } |
| | 196 | } |
| | 197 | for d in &dirs { |
| | 198 | collect_font_dir(d, 4, &mut out); |
| | 199 | } |
| | 200 | out |
| 69 | }) | 201 | }) |
| 70 | } | 202 | } |
| 71 | | 203 | |
| | 204 | #[cfg(not(target_arch = "wasm32"))] |
| | 205 | fn is_style_suffix(rest: &str) -> bool { |
| | 206 | const PREFIXES: &[&str] = &[ |
| | 207 | "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy", |
| | 208 | "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow", |
| | 209 | "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps", |
| | 210 | ]; |
| | 211 | rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p)) |
| | 212 | } |
| | 213 | |
| | 214 | #[cfg(not(target_arch = "wasm32"))] |
| | 215 | fn load_style_candidates(reg: &mut FontRegistry, fam_norm: &str, style_key: &str) { |
| | 216 | if fam_norm.is_empty() || reg.system_fonts_loaded || reg.loaded_families.contains(fam_norm) { |
| | 217 | return; |
| | 218 | } |
| | 219 | let key = (fam_norm.to_owned(), style_key.to_owned()); |
| | 220 | if !reg.loaded_style_keys.insert(key) { |
| | 221 | return; |
| | 222 | } |
| | 223 | let combined_len = fam_norm.len() + style_key.len(); |
| | 224 | for entry in system_font_index() { |
| | 225 | let exact_match = entry.stem_norm == fam_norm |
| | 226 | || (entry.stem_norm.len() == combined_len |
| | 227 | && entry.stem_norm.starts_with(fam_norm) |
| | 228 | && entry.stem_norm.ends_with(style_key)); |
| | 229 | if exact_match && reg.loaded_paths.insert(entry.path.clone()) { |
| | 230 | let _ = reg.db.load_font_file(&entry.path); |
| | 231 | } |
| | 232 | } |
| | 233 | } |
| | 234 | |
| | 235 | #[cfg(not(target_arch = "wasm32"))] |
| | 236 | fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) { |
| | 237 | if fam_norm.is_empty() || reg.system_fonts_loaded || !reg.loaded_families.insert(fam_norm.to_owned()) { |
| | 238 | return; |
| | 239 | } |
| | 240 | for entry in system_font_index() { |
| | 241 | if let Some(rest) = entry.stem_norm.strip_prefix(fam_norm) { |
| | 242 | if is_style_suffix(rest) && reg.loaded_paths.insert(entry.path.clone()) { |
| | 243 | let _ = reg.db.load_font_file(&entry.path); |
| | 244 | } |
| | 245 | } |
| | 246 | } |
| | 247 | } |
| | 248 | |
| 72 | /// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime | 249 | /// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime |
| 73 | /// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache. | 250 | /// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache. |
| 74 | pub fn register_font_bytes(bytes: Vec<u8>) { | 251 | pub fn register_font_bytes(bytes: Vec<u8>) { |
| 75 | { | 252 | { |
| 76 | let mut db = database().write().unwrap(); | 253 | let mut reg = registry().write().unwrap(); |
| 77 | db.load_font_data(bytes); | 254 | reg.db.load_font_data(bytes); |
| 78 | } | 255 | } |
| 79 | font_cache().lock().unwrap().clear(); | 256 | font_cache().lock().unwrap().clear(); |
| 80 | } | 257 | } |
| ... | @@ -83,15 +260,13 @@ pub fn register_font_bytes(bytes: Vec<u8>) { | ... | @@ -83,15 +260,13 @@ pub fn register_font_bytes(bytes: Vec<u8>) { |
| 83 | /// and clears the resolution cache. | 260 | /// and clears the resolution cache. |
| 84 | pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { | 261 | pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) { |
| 85 | { | 262 | { |
| 86 | let mut db = database().write().unwrap(); | 263 | let mut reg = registry().write().unwrap(); |
| 87 | let before: HashSet<fontdb::ID> = db.faces().map(|f| f.id).collect(); | 264 | let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect(); |
| 88 | db.load_font_data(bytes); | 265 | reg.db.load_font_data(bytes); |
| 89 | if !family.is_empty() { | 266 | if !family.is_empty() { |
| 90 | let added: Vec<fontdb::ID> = db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect(); | 267 | let added: Vec<fontdb::ID> = reg.db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect(); |
| 91 | if !added.is_empty() { | 268 | if !added.is_empty() { |
| 92 | font_aliases() | 269 | reg.aliases |
| 93 | .write() | | |
| 94 | .unwrap() | | |
| 95 | .entry(family.to_ascii_lowercase()) | 270 | .entry(family.to_ascii_lowercase()) |
| 96 | .or_default() | 271 | .or_default() |
| 97 | .extend(added); | 272 | .extend(added); |
| ... | @@ -142,25 +317,102 @@ fn metric_alias(family: &str) -> Option<&'static str> { | ... | @@ -142,25 +317,102 @@ fn metric_alias(family: &str) -> Option<&'static str> { |
| 142 | } | 317 | } |
| 143 | } | 318 | } |
| 144 | | 319 | |
| 145 | fn resolve( | 320 | #[cfg(not(target_arch = "wasm32"))] |
| | 321 | fn is_exact_face_match( |
| 146 | db: &fontdb::Database, | 322 | db: &fontdb::Database, |
| 147 | aliases: &HashMap<String, Vec<fontdb::ID>>, | 323 | id: fontdb::ID, |
| | 324 | wanted_style: &str, |
| | 325 | weight: u16, |
| | 326 | italic: bool, |
| | 327 | ) -> bool { |
| | 328 | if !wanted_style.is_empty() { |
| | 329 | let matched_name = db |
| | 330 | .with_face_data(id, |data, index| { |
| | 331 | let face = ttf_parser::Face::parse(data, index).ok()?; |
| | 332 | let names = face.names(); |
| | 333 | let name = [17, 2].into_iter().find_map(|nid| { |
| | 334 | names.into_iter().find(|n| n.name_id == nid && n.is_unicode()).and_then(|n| n.to_string()) |
| | 335 | })?; |
| | 336 | Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style)) |
| | 337 | }) |
| | 338 | .flatten() |
| | 339 | .unwrap_or(false); |
| | 340 | if matched_name { |
| | 341 | return true; |
| | 342 | } |
| | 343 | } |
| | 344 | let Some(info) = db.face(id) else { |
| | 345 | return false; |
| | 346 | }; |
| | 347 | let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }; |
| | 348 | info.weight.0 == weight && info.style == want_style |
| | 349 | } |
| | 350 | |
| | 351 | fn try_pick_family_lazy( |
| | 352 | reg: &mut FontRegistry, |
| 148 | family: &str, | 353 | family: &str, |
| 149 | style: &str, | 354 | wanted_style: &str, |
| 150 | ) -> Option<Font> { | 355 | weight: u16, |
| | 356 | italic: bool, |
| | 357 | ) -> Option<fontdb::ID> { |
| | 358 | if family.is_empty() { |
| | 359 | return None; |
| | 360 | } |
| | 361 | #[cfg(not(target_arch = "wasm32"))] |
| | 362 | { |
| | 363 | let fam_norm = norm_alnum(family); |
| | 364 | let style_key = if wanted_style.is_empty() { "regular" } else { wanted_style }; |
| | 365 | if !reg.system_fonts_loaded |
| | 366 | && !reg.loaded_families.contains(&fam_norm) |
| | 367 | && !reg.aliases.contains_key(&family.to_ascii_lowercase()) |
| | 368 | { |
| | 369 | load_style_candidates(reg, &fam_norm, style_key); |
| | 370 | if let Some(id) = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) { |
| | 371 | if is_exact_face_match(&reg.db, id, wanted_style, weight, italic) { |
| | 372 | return Some(id); |
| | 373 | } |
| | 374 | } |
| | 375 | load_family_candidates(reg, &fam_norm); |
| | 376 | } |
| | 377 | } |
| | 378 | pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) |
| | 379 | } |
| | 380 | |
| | 381 | fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> { |
| 151 | let (weight, italic) = parse_style(style); | 382 | let (weight, italic) = parse_style(style); |
| 152 | let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase(); | 383 | let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase(); |
| 153 | let id = std::iter::once(family) | 384 | |
| 154 | .chain(metric_alias(family)) | 385 | let mut id = try_pick_family_lazy(reg, family, &wanted, weight, italic) |
| 155 | .chain(FALLBACK_FAMILIES) | 386 | .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic))); |
| 156 | .find_map(|name| pick(db, aliases, name, &wanted, weight, italic)) | 387 | |
| 157 | .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) | 388 | #[cfg(not(target_arch = "wasm32"))] |
| 158 | .or_else(|| db.faces().map(|f| f.id).next())?; | 389 | if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded { |
| 159 | let info = db.face(id)?; | 390 | reg.ensure_system_fonts_loaded(); |
| 160 | let data = db.with_face_data(id, |data, _| data.to_vec())?; | 391 | 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))); |
| | 393 | } |
| | 394 | |
| | 395 | if id.is_none() { |
| | 396 | id = FALLBACK_FAMILIES |
| | 397 | .iter() |
| | 398 | .find_map(|fb| try_pick_family_lazy(reg, fb, &wanted, weight, italic)); |
| | 399 | } |
| | 400 | |
| | 401 | #[cfg(not(target_arch = "wasm32"))] |
| | 402 | if id.is_none() && !reg.system_fonts_loaded { |
| | 403 | reg.ensure_system_fonts_loaded(); |
| | 404 | } |
| | 405 | |
| | 406 | let id = id |
| | 407 | .or_else(|| reg.db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) |
| | 408 | .or_else(|| reg.db.faces().map(|f| f.id).next())?; |
| | 409 | |
| | 410 | let info = reg.db.face(id)?; |
| | 411 | let data = reg.db.with_face_data(id, |data, _| data.to_vec())?; |
| 161 | let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 }; | 412 | let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 }; |
| 162 | Face::from_slice(&data, info.index)?; | 413 | Face::from_slice(&data, info.index)?; |
| 163 | Some(Font { data, index: info.index, weight, lean }) | 414 | let font_id = NEXT_FONT_ID.fetch_add(1, Ordering::Relaxed); |
| | 415 | Some(Font { id: font_id, data, index: info.index, weight, lean }) |
| 164 | } | 416 | } |
| 165 | | 417 | |
| 166 | /// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest | 418 | /// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest |
| ... | @@ -186,20 +438,22 @@ fn pick( | ... | @@ -186,20 +438,22 @@ fn pick( |
| 186 | .collect(); | 438 | .collect(); |
| 187 | candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index))); | 439 | candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index))); |
| 188 | let first = candidates.first()?; | 440 | let first = candidates.first()?; |
| 189 | let exact = candidates.iter().find(|f| { | 441 | if !wanted_style.is_empty() { |
| 190 | db.with_face_data(f.id, |data, index| { | 442 | let exact = candidates.iter().find(|f| { |
| 191 | let face = ttf_parser::Face::parse(data, index).ok()?; | 443 | db.with_face_data(f.id, |data, index| { |
| 192 | let names = face.names(); | 444 | let face = ttf_parser::Face::parse(data, index).ok()?; |
| 193 | let name = [17, 2].into_iter().find_map(|id| { | 445 | let names = face.names(); |
| 194 | names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string()) | 446 | let name = [17, 2].into_iter().find_map(|id| { |
| 195 | })?; | 447 | names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string()) |
| 196 | Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style)) | 448 | })?; |
| 197 | }) | 449 | Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style)) |
| 198 | .flatten() | 450 | }) |
| 199 | .unwrap_or(false) | 451 | .flatten() |
| 200 | }); | 452 | .unwrap_or(false) |
| 201 | if let Some(face) = exact { | 453 | }); |
| 202 | return Some(face.id); | 454 | if let Some(face) = exact { |
| | 455 | return Some(face.id); |
| | 456 | } |
| 203 | } | 457 | } |
| 204 | if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) { | 458 | if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) { |
| 205 | return db.query(&fontdb::Query { | 459 | return db.query(&fontdb::Query { |
| ... | @@ -451,12 +705,20 @@ fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> { | ... | @@ -451,12 +705,20 @@ fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> { |
| 451 | | 705 | |
| 452 | struct PlacedGlyph { | 706 | struct PlacedGlyph { |
| 453 | commands: Vec<Command>, | 707 | commands: Vec<Command>, |
| 454 | char_idx: usize, | 708 | } |
| | 709 | |
| | 710 | struct GlyphSpec { |
| | 711 | font: Arc<Font>, |
| | 712 | glyph_id: GlyphId, |
| | 713 | font_px: f32, |
| | 714 | shear: f32, |
| 455 | outline_w: f32, | 715 | outline_w: f32, |
| | 716 | abs_x: f32, |
| | 717 | abs_y: f32, |
| 456 | } | 718 | } |
| 457 | | 719 | |
| 458 | struct LayoutLine { | 720 | struct LayoutSpecLine { |
| 459 | glyphs: Vec<PlacedGlyph>, | 721 | glyphs: Vec<GlyphSpec>, |
| 460 | width: f32, | 722 | width: f32, |
| 461 | ascent: f32, | 723 | ascent: f32, |
| 462 | descent: f32, | 724 | descent: f32, |
| ... | @@ -470,7 +732,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3 | ... | @@ -470,7 +732,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3 |
| 470 | (font_px, asc_em * font_px, desc_em * font_px) | 732 | (font_px, asc_em * font_px, desc_em * font_px) |
| 471 | } | 733 | } |
| 472 | | 734 | |
| 473 | fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> { | 735 | fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> { |
| 474 | let [w, h] = dims; | 736 | let [w, h] = dims; |
| 475 | let total_chars = params.text.chars().count(); | 737 | let total_chars = params.text.chars().count(); |
| 476 | if total_chars == 0 || params.size_norm <= 1e-4 { | 738 | if total_chars == 0 || params.size_norm <= 1e-4 { |
| ... | @@ -481,7 +743,6 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec | ... | @@ -481,7 +743,6 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec |
| 481 | if c_start >= c_end || c_start >= total_chars { | 743 | if c_start >= c_end || c_start >= total_chars { |
| 482 | return None; | 744 | return None; |
| 483 | } | 745 | } |
| 484 | let styles = resolve_char_styles(params); | | |
| 485 | let wf = w as f32; | 746 | let wf = w as f32; |
| 486 | let hf = h as f32; | 747 | let hf = h as f32; |
| 487 | let base_font = Font::find(params.font_family, params.font_style)?; | 748 | let base_font = Font::find(params.font_family, params.font_style)?; |
| ... | @@ -489,87 +750,141 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec | ... | @@ -489,87 +750,141 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec |
| 489 | | 750 | |
| 490 | let mut lines = Vec::new(); | 751 | let mut lines = Vec::new(); |
| 491 | let mut char_cursor = 0usize; | 752 | let mut char_cursor = 0usize; |
| 492 | for raw_line in params.text.split('\n') { | 753 | |
| 493 | let raw_char_len = raw_line.chars().count(); | 754 | if params.cls.is_empty() { |
| 494 | let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); | 755 | let (font_px, asc, desc) = size_metrics(&base_face, params.size_norm, wf); |
| 495 | let line_chars: Vec<char> = line_str.chars().collect(); | 756 | let top_anchor = (font_px - desc).max(0.0); |
| 496 | let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new(); | 757 | let extra_track = (params.tracking - 1.0) * params.size_norm * wf; |
| 497 | let mut line_max_size = 0.0_f32; | 758 | let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 { |
| 498 | let mut max_asc = 0.0_f32; | 759 | (params.outline_thickness_norm * params.size_norm * wf).clamp(1.0, 128.0) |
| 499 | let mut max_desc = 0.0_f32; | | |
| 500 | let mut max_top_anchor = 0.0_f32; | | |
| 501 | | | |
| 502 | if line_chars.is_empty() { | | |
| 503 | let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm); | | |
| 504 | let (font_px, asc, desc) = size_metrics(&base_face, st, wf); | | |
| 505 | max_asc = asc; | | |
| 506 | max_desc = desc; | | |
| 507 | max_top_anchor = (font_px - desc).max(0.0); | | |
| 508 | } else { | 760 | } else { |
| 509 | let mut r0 = 0usize; | 761 | 0.0 |
| 510 | while r0 < line_chars.len() { | 762 | }; |
| 511 | let st0 = &styles[char_cursor + r0]; | 763 | for raw_line in params.text.split('\n') { |
| 512 | let mut r1 = r0 + 1; | 764 | let raw_char_len = raw_line.chars().count(); |
| 513 | while r1 < line_chars.len() { | 765 | let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); |
| 514 | let st1 = &styles[char_cursor + r1]; | 766 | let mut line_glyphs = Vec::new(); |
| 515 | if st1.family != st0.family | 767 | let width = if line_str.is_empty() { |
| 516 | || st1.style != st0.style | 768 | 0.0 |
| 517 | || (st1.size_norm - st0.size_norm).abs() > 1e-5 | 769 | } else { |
| 518 | { | 770 | let shaped = shape_line(&base_face, line_str, font_px, extra_track); |
| 519 | break; | 771 | line_glyphs.reserve(shaped.glyphs.len()); |
| | 772 | for g in &shaped.glyphs { |
| | 773 | let idx = char_cursor + g.char_index; |
| | 774 | if idx < c_start || idx >= c_end { |
| | 775 | continue; |
| 520 | } | 776 | } |
| 521 | r1 += 1; | 777 | line_glyphs.push(GlyphSpec { |
| | 778 | font: Arc::clone(&base_font), |
| | 779 | glyph_id: g.id, |
| | 780 | font_px, |
| | 781 | shear: -params.shear_x, |
| | 782 | outline_w, |
| | 783 | abs_x: g.x, |
| | 784 | abs_y: -g.y, |
| | 785 | }); |
| 522 | } | 786 | } |
| 523 | let run_str: String = line_chars[r0..r1].iter().collect(); | 787 | shaped.width |
| 524 | let font = Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font)); | 788 | }; |
| 525 | let face = font.face(); | 789 | lines.push(LayoutSpecLine { |
| 526 | let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf); | 790 | glyphs: line_glyphs, |
| 527 | max_asc = max_asc.max(asc); | 791 | width, |
| 528 | max_desc = max_desc.max(desc); | 792 | ascent: asc, |
| 529 | max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0)); | 793 | descent: desc, |
| 530 | line_max_size = line_max_size.max(st0.size_norm); | 794 | top_anchor, |
| 531 | let extra_track = (params.tracking - 1.0) * st0.size_norm * wf; | 795 | }); |
| 532 | let shaped = shape_line(&face, &run_str, font_px, extra_track); | 796 | char_cursor += raw_char_len + 1; |
| 533 | shaped_runs.push((r0, r1, font, font_px, shaped)); | | |
| 534 | r0 = r1; | | |
| 535 | } | | |
| 536 | } | 797 | } |
| 537 | | 798 | } else { |
| 538 | let mut total_w = 0.0_f32; | 799 | let styles = resolve_char_styles(params); |
| 539 | let mut line_glyphs = Vec::new(); | 800 | for raw_line in params.text.split('\n') { |
| 540 | for (ri, &(r0, _, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() { | 801 | let raw_char_len = raw_line.chars().count(); |
| 541 | if ri > 0 { | 802 | let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); |
| 542 | let st_prev = &styles[char_cursor + r0 - 1]; | 803 | let line_chars: Vec<char> = line_str.chars().collect(); |
| 543 | total_w += (params.tracking - 1.0) * st_prev.size_norm * wf; | 804 | let mut shaped_runs: Vec<(usize, Arc<Font>, f32, ShapedLine)> = Vec::new(); |
| 544 | } | 805 | let mut max_asc = 0.0_f32; |
| 545 | let face = font.face(); | 806 | let mut max_desc = 0.0_f32; |
| 546 | let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 { | 807 | let mut max_top_anchor = 0.0_f32; |
| 547 | let size_px = styles[char_cursor + r0].size_norm * wf; | 808 | |
| 548 | (params.outline_thickness_norm * size_px).clamp(1.0, 128.0) | 809 | if line_chars.is_empty() { |
| | 810 | let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm); |
| | 811 | let (font_px, asc, desc) = size_metrics(&base_face, st, wf); |
| | 812 | max_asc = asc; |
| | 813 | max_desc = desc; |
| | 814 | max_top_anchor = (font_px - desc).max(0.0); |
| 549 | } else { | 815 | } else { |
| 550 | 0.0 | 816 | let mut r0 = 0usize; |
| 551 | }; | 817 | while r0 < line_chars.len() { |
| 552 | for g in &shaped.glyphs { | 818 | let st0 = &styles[char_cursor + r0]; |
| 553 | let idx = char_cursor + r0 + g.char_index; | 819 | let mut r1 = r0 + 1; |
| 554 | if idx < c_start || idx >= c_end { | 820 | while r1 < line_chars.len() { |
| 555 | continue; | 821 | let st1 = &styles[char_cursor + r1]; |
| | 822 | if st1.family != st0.family |
| | 823 | || st1.style != st0.style |
| | 824 | || (st1.size_norm - st0.size_norm).abs() > 1e-5 |
| | 825 | { |
| | 826 | break; |
| | 827 | } |
| | 828 | r1 += 1; |
| | 829 | } |
| | 830 | let run_str: String = line_chars[r0..r1].iter().collect(); |
| | 831 | let font = if st0.family == params.font_family && st0.style == params.font_style { |
| | 832 | Arc::clone(&base_font) |
| | 833 | } else { |
| | 834 | Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font)) |
| | 835 | }; |
| | 836 | let face = font.face(); |
| | 837 | let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf); |
| | 838 | max_asc = max_asc.max(asc); |
| | 839 | max_desc = max_desc.max(desc); |
| | 840 | max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0)); |
| | 841 | let extra_track = (params.tracking - 1.0) * st0.size_norm * wf; |
| | 842 | let shaped = shape_line(&face, &run_str, font_px, extra_track); |
| | 843 | shaped_runs.push((r0, font, font_px, shaped)); |
| | 844 | r0 = r1; |
| 556 | } | 845 | } |
| 557 | let st = &styles[idx]; | | |
| 558 | let local_origin = [total_w + g.x + st.dx * wf, -g.y - st.dy * wf]; | | |
| 559 | let cmds = glyph_path(font, &face, g.id, font_px, local_origin, -st.shear_x); | | |
| 560 | line_glyphs.push(PlacedGlyph { commands: cmds, char_idx: idx, outline_w }); | | |
| 561 | } | 846 | } |
| 562 | total_w += shaped.width; | 847 | |
| 563 | } | 848 | let mut total_w = 0.0_f32; |
| 564 | let _ = line_max_size; | 849 | let mut line_glyphs = Vec::new(); |
| 565 | lines.push(LayoutLine { | 850 | for (ri, &(r0, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() { |
| 566 | glyphs: line_glyphs, | 851 | if ri > 0 { |
| 567 | width: total_w, | 852 | let st_prev = &styles[char_cursor + r0 - 1]; |
| 568 | ascent: max_asc, | 853 | total_w += (params.tracking - 1.0) * st_prev.size_norm * wf; |
| 569 | descent: max_desc, | 854 | } |
| 570 | top_anchor: max_top_anchor, | 855 | let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 { |
| 571 | }); | 856 | let size_px = styles[char_cursor + r0].size_norm * wf; |
| 572 | char_cursor += raw_char_len + 1; | 857 | (params.outline_thickness_norm * size_px).clamp(1.0, 128.0) |
| | 858 | } else { |
| | 859 | 0.0 |
| | 860 | }; |
| | 861 | for g in &shaped.glyphs { |
| | 862 | let idx = char_cursor + r0 + g.char_index; |
| | 863 | if idx < c_start || idx >= c_end { |
| | 864 | continue; |
| | 865 | } |
| | 866 | let st = &styles[idx]; |
| | 867 | line_glyphs.push(GlyphSpec { |
| | 868 | font: Arc::clone(font), |
| | 869 | glyph_id: g.id, |
| | 870 | font_px, |
| | 871 | shear: -st.shear_x, |
| | 872 | outline_w, |
| | 873 | abs_x: total_w + g.x + st.dx * wf, |
| | 874 | abs_y: -g.y - st.dy * wf, |
| | 875 | }); |
| | 876 | } |
| | 877 | total_w += shaped.width; |
| | 878 | } |
| | 879 | lines.push(LayoutSpecLine { |
| | 880 | glyphs: line_glyphs, |
| | 881 | width: total_w, |
| | 882 | ascent: max_asc, |
| | 883 | descent: max_desc, |
| | 884 | top_anchor: max_top_anchor, |
| | 885 | }); |
| | 886 | char_cursor += raw_char_len + 1; |
| | 887 | } |
| 573 | } | 888 | } |
| 574 | | 889 | |
| 575 | let cx = params.center[0] * wf; | 890 | let cx = params.center[0] * wf; |
| ... | @@ -602,37 +917,146 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec | ... | @@ -602,37 +917,146 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec |
| 602 | for (li, line) in lines.into_iter().enumerate() { | 917 | for (li, line) in lines.into_iter().enumerate() { |
| 603 | let start_x = cx - line.width * h_frac; | 918 | let start_x = cx - line.width * h_frac; |
| 604 | let base_y = baseline_0 + baselines[li]; | 919 | let base_y = baseline_0 + baselines[li]; |
| 605 | for mut pg in line.glyphs { | 920 | for mut spec in line.glyphs { |
| 606 | for cmd in &mut pg.commands { | 921 | spec.abs_x += start_x; |
| 607 | match cmd { | 922 | spec.abs_y += base_y; |
| 608 | Command::MoveTo(p) | Command::LineTo(p) => { | 923 | out.push(spec); |
| 609 | p.x += start_x; | | |
| 610 | p.y += base_y; | | |
| 611 | } | | |
| 612 | Command::QuadTo(c, p) => { | | |
| 613 | c.x += start_x; | | |
| 614 | c.y += base_y; | | |
| 615 | p.x += start_x; | | |
| 616 | p.y += base_y; | | |
| 617 | } | | |
| 618 | Command::CurveTo(c1, c2, p) => { | | |
| 619 | c1.x += start_x; | | |
| 620 | c1.y += base_y; | | |
| 621 | c2.x += start_x; | | |
| 622 | c2.y += base_y; | | |
| 623 | p.x += start_x; | | |
| 624 | p.y += base_y; | | |
| 625 | } | | |
| 626 | Command::Close => {} | | |
| 627 | } | | |
| 628 | } | | |
| 629 | let _ = pg.char_idx; | | |
| 630 | out.push(pg); | | |
| 631 | } | 924 | } |
| 632 | } | 925 | } |
| 633 | Some((out, total_chars)) | 926 | Some((out, total_chars)) |
| 634 | } | 927 | } |
| 635 | | 928 | |
| | 929 | fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> { |
| | 930 | let (specs, total_chars) = layout_glyph_specs(dims, params)?; |
| | 931 | let mut out = Vec::with_capacity(specs.len()); |
| | 932 | for spec in &specs { |
| | 933 | let face = spec.font.face(); |
| | 934 | let commands = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, [spec.abs_x, spec.abs_y], spec.shear); |
| | 935 | out.push(PlacedGlyph { commands }); |
| | 936 | } |
| | 937 | Some((out, total_chars)) |
| | 938 | } |
| | 939 | |
| | 940 | const GLYPH_BASELINE_ANCHOR: f32 = 256.0; |
| | 941 | const GLYPH_BASELINE_ANCHOR_I32: i32 = 256; |
| | 942 | const MAX_GLYPH_CACHE_ENTRIES: usize = 4096; |
| | 943 | const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024; |
| | 944 | |
| | 945 | #[derive(Clone, Copy, PartialEq, Eq, Hash)] |
| | 946 | struct GlyphCacheKey { |
| | 947 | font_id: u64, |
| | 948 | glyph_id: u16, |
| | 949 | size_bits: u32, |
| | 950 | lean_bits: u32, |
| | 951 | stroke_bits: u32, |
| | 952 | sub_x_bits: u32, |
| | 953 | sub_y_bits: u32, |
| | 954 | } |
| | 955 | |
| | 956 | struct CachedGlyphCoverage { |
| | 957 | fill: Option<Coverage>, |
| | 958 | stroke: Option<Coverage>, |
| | 959 | bytes: usize, |
| | 960 | } |
| | 961 | |
| | 962 | struct GlyphCache { |
| | 963 | map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>, |
| | 964 | order: VecDeque<GlyphCacheKey>, |
| | 965 | total_bytes: usize, |
| | 966 | } |
| | 967 | |
| | 968 | impl GlyphCache { |
| | 969 | fn new() -> Self { |
| | 970 | Self { |
| | 971 | map: HashMap::new(), |
| | 972 | order: VecDeque::new(), |
| | 973 | total_bytes: 0, |
| | 974 | } |
| | 975 | } |
| | 976 | |
| | 977 | fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> { |
| | 978 | self.map.get(key).cloned() |
| | 979 | } |
| | 980 | |
| | 981 | fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) { |
| | 982 | if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) { |
| | 983 | return; |
| | 984 | } |
| | 985 | 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 { |
| | 987 | break; |
| | 988 | }; |
| | 989 | if let Some(removed) = self.map.remove(&old_key) { |
| | 990 | self.total_bytes = self.total_bytes.saturating_sub(removed.bytes); |
| | 991 | } |
| | 992 | } |
| | 993 | self.total_bytes += val.bytes; |
| | 994 | self.order.push_back(key); |
| | 995 | self.map.insert(key, val); |
| | 996 | } |
| | 997 | } |
| | 998 | |
| | 999 | fn glyph_cache() -> &'static Mutex<GlyphCache> { |
| | 1000 | static CACHE: OnceLock<Mutex<GlyphCache>> = OnceLock::new(); |
| | 1001 | CACHE.get_or_init(|| Mutex::new(GlyphCache::new())) |
| | 1002 | } |
| | 1003 | |
| | 1004 | fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) { |
| | 1005 | let ix = spec.abs_x.floor() as i32; |
| | 1006 | let iy = spec.abs_y.floor() as i32; |
| | 1007 | let fx = spec.abs_x - ix as f32; |
| | 1008 | let fy = spec.abs_y - iy as f32; |
| | 1009 | |
| | 1010 | let total_lean = spec.font.lean + spec.shear; |
| | 1011 | let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean }; |
| | 1012 | let stroke_bits = if want_outline { |
| | 1013 | spec.outline_w.to_bits() |
| | 1014 | } else { |
| | 1015 | 0 |
| | 1016 | }; |
| | 1017 | let key = GlyphCacheKey { |
| | 1018 | font_id: spec.font.id, |
| | 1019 | glyph_id: spec.glyph_id.0, |
| | 1020 | size_bits: spec.font_px.to_bits(), |
| | 1021 | lean_bits: lean_norm.to_bits(), |
| | 1022 | stroke_bits, |
| | 1023 | sub_x_bits: if fx == 0.0 { 0 } else { fx.to_bits() }, |
| | 1024 | sub_y_bits: if fy == 0.0 { 0 } else { fy.to_bits() }, |
| | 1025 | }; |
| | 1026 | |
| | 1027 | if let Some(hit) = glyph_cache().lock().unwrap().get(&key) { |
| | 1028 | return (ix, iy, hit); |
| | 1029 | } |
| | 1030 | |
| | 1031 | // Anchor outlines near 256px so zeno's flattening precision matches full-canvas rasterization. |
| | 1032 | let sub_origin = [GLYPH_BASELINE_ANCHOR + fx, GLYPH_BASELINE_ANCHOR + fy]; |
| | 1033 | let face = spec.font.face(); |
| | 1034 | let path = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, sub_origin, spec.shear); |
| | 1035 | let fill_cov = fill(&path).map(|mut c| { |
| | 1036 | c.left -= GLYPH_BASELINE_ANCHOR_I32; |
| | 1037 | c.top -= GLYPH_BASELINE_ANCHOR_I32; |
| | 1038 | c |
| | 1039 | }); |
| | 1040 | let stroke_cov = if want_outline { |
| | 1041 | stroke(&path, spec.outline_w).map(|mut c| { |
| | 1042 | c.left -= GLYPH_BASELINE_ANCHOR_I32; |
| | 1043 | c.top -= GLYPH_BASELINE_ANCHOR_I32; |
| | 1044 | c |
| | 1045 | }) |
| | 1046 | } else { |
| | 1047 | None |
| | 1048 | }; |
| | 1049 | let bytes = fill_cov.as_ref().map_or(0, |c| c.data.len()) |
| | 1050 | + stroke_cov.as_ref().map_or(0, |c| c.data.len()); |
| | 1051 | let entry = Arc::new(CachedGlyphCoverage { |
| | 1052 | fill: fill_cov, |
| | 1053 | stroke: stroke_cov, |
| | 1054 | bytes, |
| | 1055 | }); |
| | 1056 | glyph_cache().lock().unwrap().insert(key, Arc::clone(&entry)); |
| | 1057 | (ix, iy, entry) |
| | 1058 | } |
| | 1059 | |
| 636 | fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) { | 1060 | fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) { |
| 637 | if !sigma.is_finite() || sigma < 0.05 { | 1061 | if !sigma.is_finite() || sigma < 0.05 { |
| 638 | return (0, vec![1.0]); | 1062 | return (0, vec![1.0]); |
| ... | @@ -730,20 +1154,22 @@ fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32, | ... | @@ -730,20 +1154,22 @@ fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32, |
| 730 | } | 1154 | } |
| 731 | } | 1155 | } |
| 732 | | 1156 | |
| 733 | fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) { | 1157 | fn blit_plane_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) { |
| | 1158 | let c_left = c.left + offset[0]; |
| | 1159 | let c_top = c.top + offset[1]; |
| 734 | let cw = c.width as i32; | 1160 | let cw = c.width as i32; |
| 735 | let ch = c.height as i32; | 1161 | let ch = c.height as i32; |
| 736 | let x0 = (origin[0] - c.left).max(0); | 1162 | let x0 = (origin[0] - c_left).max(0); |
| 737 | let y0 = (origin[1] - c.top).max(0); | 1163 | let y0 = (origin[1] - c_top).max(0); |
| 738 | let x1 = (origin[0] + tw as i32 - c.left).min(cw); | 1164 | let x1 = (origin[0] + tw as i32 - c_left).min(cw); |
| 739 | let y1 = (origin[1] + th as i32 - c.top).min(ch); | 1165 | let y1 = (origin[1] + th as i32 - c_top).min(ch); |
| 740 | if x0 >= x1 || y0 >= y1 { | 1166 | if x0 >= x1 || y0 >= y1 { |
| 741 | return; | 1167 | return; |
| 742 | } | 1168 | } |
| 743 | let span = (x1 - x0) as usize; | 1169 | let span = (x1 - x0) as usize; |
| 744 | let dst_x0 = (c.left + x0 - origin[0]) as usize; | 1170 | let dst_x0 = (c_left + x0 - origin[0]) as usize; |
| 745 | for y in y0..y1 { | 1171 | for y in y0..y1 { |
| 746 | let py = (c.top + y - origin[1]) as usize; | 1172 | let py = (c_top + y - origin[1]) as usize; |
| 747 | let src_start = y as usize * c.width as usize + x0 as usize; | 1173 | let src_start = y as usize * c.width as usize + x0 as usize; |
| 748 | let src_row = &c.data[src_start..src_start + span]; | 1174 | let src_row = &c.data[src_start..src_start + span]; |
| 749 | let dst_start = py * tw + dst_x0; | 1175 | let dst_start = py * tw + dst_x0; |
| ... | @@ -756,6 +1182,32 @@ fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: & | ... | @@ -756,6 +1182,32 @@ fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: & |
| 756 | } | 1182 | } |
| 757 | } | 1183 | } |
| 758 | | 1184 | |
| | 1185 | fn blit_plane_u8_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [u8]) { |
| | 1186 | let c_left = c.left + offset[0]; |
| | 1187 | let c_top = c.top + offset[1]; |
| | 1188 | let cw = c.width as i32; |
| | 1189 | let ch = c.height as i32; |
| | 1190 | let x0 = (origin[0] - c_left).max(0); |
| | 1191 | let y0 = (origin[1] - c_top).max(0); |
| | 1192 | let x1 = (origin[0] + tw as i32 - c_left).min(cw); |
| | 1193 | let y1 = (origin[1] + th as i32 - c_top).min(ch); |
| | 1194 | if x0 >= x1 || y0 >= y1 { |
| | 1195 | return; |
| | 1196 | } |
| | 1197 | let span = (x1 - x0) as usize; |
| | 1198 | let dst_x0 = (c_left + x0 - origin[0]) as usize; |
| | 1199 | for y in y0..y1 { |
| | 1200 | let py = (c_top + y - origin[1]) as usize; |
| | 1201 | let src_start = y as usize * c.width as usize + x0 as usize; |
| | 1202 | let src_row = &c.data[src_start..src_start + span]; |
| | 1203 | let dst_start = py * tw + dst_x0; |
| | 1204 | let dst_row = &mut plane[dst_start..dst_start + span]; |
| | 1205 | for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) { |
| | 1206 | *d = (*d).max(a); |
| | 1207 | } |
| | 1208 | } |
| | 1209 | } |
| | 1210 | |
| 759 | /// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and | 1211 | /// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and |
| 760 | /// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer. | 1212 | /// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer. |
| 761 | pub fn rasterize_text_plus_rich( | 1213 | pub fn rasterize_text_plus_rich( |
| ... | @@ -769,10 +1221,10 @@ pub fn rasterize_text_plus_rich( | ... | @@ -769,10 +1221,10 @@ pub fn rasterize_text_plus_rich( |
| 769 | if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 { | 1221 | if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 { |
| 770 | return empty(); | 1222 | return empty(); |
| 771 | } | 1223 | } |
| 772 | let Some((glyphs, _)) = layout_glyphs(dims, params) else { | 1224 | let Some((specs, _)) = layout_glyph_specs(dims, params) else { |
| 773 | return empty(); | 1225 | return empty(); |
| 774 | }; | 1226 | }; |
| 775 | if glyphs.is_empty() { | 1227 | if specs.is_empty() { |
| 776 | return empty(); | 1228 | return empty(); |
| 777 | } | 1229 | } |
| 778 | | 1230 | |
| ... | @@ -788,31 +1240,31 @@ pub fn rasterize_text_plus_rich( | ... | @@ -788,31 +1240,31 @@ pub fn rasterize_text_plus_rich( |
| 788 | let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1); | 1240 | let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1); |
| 789 | | 1241 | |
| 790 | let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); | 1242 | let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); |
| 791 | let mut grow = |c: &Coverage, pad: i32| { | 1243 | let mut grow = |c: &Coverage, ox: i32, oy: i32, pad: i32| { |
| 792 | min_x = min_x.min(c.left.saturating_sub(pad)); | 1244 | let left = c.left.saturating_add(ox); |
| 793 | min_y = min_y.min(c.top.saturating_sub(pad)); | 1245 | let top = c.top.saturating_add(oy); |
| 794 | max_x = max_x.max((c.left + c.width as i32).saturating_add(pad)); | 1246 | min_x = min_x.min(left.saturating_sub(pad)); |
| 795 | max_y = max_y.max((c.top + c.height as i32).saturating_add(pad)); | 1247 | min_y = min_y.min(top.saturating_sub(pad)); |
| | 1248 | max_x = max_x.max((left + c.width as i32).saturating_add(pad)); |
| | 1249 | max_y = max_y.max((top + c.height as i32).saturating_add(pad)); |
| 796 | }; | 1250 | }; |
| 797 | | 1251 | |
| 798 | let mut placed = Vec::with_capacity(glyphs.len()); | 1252 | let mut placed = Vec::with_capacity(specs.len()); |
| 799 | let mut any_outline = false; | 1253 | let mut any_outline = false; |
| 800 | for g in &glyphs { | 1254 | for spec in &specs { |
| 801 | let f = fill(&g.commands); | 1255 | if !spec.abs_x.is_finite() || !spec.abs_y.is_finite() { |
| 802 | let l = if has_outline && g.outline_w > 1e-3 { | 1256 | continue; |
| 803 | let s = stroke(&g.commands, g.outline_w); | 1257 | } |
| 804 | any_outline |= s.is_some(); | 1258 | let want_outline = has_outline && spec.outline_w > 1e-3; |
| 805 | s | 1259 | let (ix, iy, cov) = cached_glyph_coverage(spec, want_outline); |
| 806 | } else { | 1260 | if let Some(c) = &cov.fill { |
| 807 | None | 1261 | grow(c, ix, iy, eff_pad); |
| 808 | }; | | |
| 809 | if let Some(c) = &f { | | |
| 810 | grow(c, eff_pad); | | |
| 811 | } | 1262 | } |
| 812 | if let Some(c) = &l { | 1263 | if let Some(c) = &cov.stroke { |
| 813 | grow(c, eff_pad); | 1264 | any_outline = true; |
| | 1265 | grow(c, ix, iy, eff_pad); |
| 814 | } | 1266 | } |
| 815 | placed.push((f, l)); | 1267 | placed.push((ix, iy, cov)); |
| 816 | } | 1268 | } |
| 817 | if min_x > max_x || min_y > max_y { | 1269 | if min_x > max_x || min_y > max_y { |
| 818 | return empty(); | 1270 | return empty(); |
| ... | @@ -828,14 +1280,47 @@ pub fn rasterize_text_plus_rich( | ... | @@ -828,14 +1280,47 @@ pub fn rasterize_text_plus_rich( |
| 828 | let tw = (end_x - origin_x) as usize; | 1280 | let tw = (end_x - origin_x) as usize; |
| 829 | let th = (end_y - origin_y) as usize; | 1281 | let th = (end_y - origin_y) as usize; |
| 830 | | 1282 | |
| | 1283 | let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999)); |
| | 1284 | let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999)); |
| | 1285 | let (fc, oc) = (params.fill_rgba, params.outline_rgba); |
| | 1286 | let mut out = vec![0u8; tw * th * 4]; |
| | 1287 | |
| | 1288 | if !any_outline && sx1 <= 0.05 && sy1 <= 0.05 { |
| | 1289 | let mut fill_u8 = vec![0u8; tw * th]; |
| | 1290 | for (ix, iy, cov) in &placed { |
| | 1291 | if let Some(c) = &cov.fill { |
| | 1292 | blit_plane_u8_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_u8); |
| | 1293 | } |
| | 1294 | } |
| | 1295 | let f_scale = fc[3] * glow1; |
| | 1296 | let mut lut = [[0u8; 4]; 256]; |
| | 1297 | for (a_u8, entry) in lut.iter_mut().enumerate().skip(1) { |
| | 1298 | let fa = ((a_u8 as f32 / 255.0) * f_scale).clamp(0.0, 1.0); |
| | 1299 | if fa > 0.0 { |
| | 1300 | *entry = [ |
| | 1301 | (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8, |
| | 1302 | (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8, |
| | 1303 | (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8, |
| | 1304 | (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8, |
| | 1305 | ]; |
| | 1306 | } |
| | 1307 | } |
| | 1308 | for (px, &a) in out.chunks_exact_mut(4).zip(fill_u8.iter()) { |
| | 1309 | if a != 0 { |
| | 1310 | px.copy_from_slice(&lut[a as usize]); |
| | 1311 | } |
| | 1312 | } |
| | 1313 | return ([tw as u32, th as u32], [origin_x, origin_y], out); |
| | 1314 | } |
| | 1315 | |
| 831 | let mut fill_plane = vec![0.0_f32; tw * th]; | 1316 | let mut fill_plane = vec![0.0_f32; tw * th]; |
| 832 | let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }]; | 1317 | let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }]; |
| 833 | for (f, l) in &placed { | 1318 | for (ix, iy, cov) in &placed { |
| 834 | if let Some(c) = f { | 1319 | if let Some(c) = &cov.fill { |
| 835 | blit_plane_max(c, [origin_x, origin_y], tw, th, &mut fill_plane); | 1320 | blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_plane); |
| 836 | } | 1321 | } |
| 837 | if let Some(c) = l { | 1322 | if let Some(c) = &cov.stroke { |
| 838 | blit_plane_max(c, [origin_x, origin_y], tw, th, &mut line_plane); | 1323 | blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut line_plane); |
| 839 | } | 1324 | } |
| 840 | } | 1325 | } |
| 841 | | 1326 | |
| ... | @@ -846,10 +1331,6 @@ pub fn rasterize_text_plus_rich( | ... | @@ -846,10 +1331,6 @@ pub fn rasterize_text_plus_rich( |
| 846 | apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2); | 1331 | apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2); |
| 847 | } | 1332 | } |
| 848 | | 1333 | |
| 849 | let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999)); | | |
| 850 | let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999)); | | |
| 851 | let (fc, oc) = (params.fill_rgba, params.outline_rgba); | | |
| 852 | let mut out = vec![0u8; tw * th * 4]; | | |
| 853 | if any_outline { | 1334 | if any_outline { |
| 854 | let f_scale = fc[3] * glow1; | 1335 | let f_scale = fc[3] * glow1; |
| 855 | let o_scale = oc[3] * glow2; | 1336 | let o_scale = oc[3] * glow2; |
| ... | @@ -1956,4 +2437,82 @@ mod tests { | ... | @@ -1956,4 +2437,82 @@ mod tests { |
| 1956 | } | 2437 | } |
| 1957 | } | 2438 | } |
| 1958 | } | 2439 | } |
| | 2440 | |
| | 2441 | #[test] |
| | 2442 | fn glyph_cache_is_deterministic_and_bounded() { |
| | 2443 | let p = RichTextPlusParams { |
| | 2444 | text: "Mississippi 1234", |
| | 2445 | font_family: "Helvetica", |
| | 2446 | font_style: "Regular", |
| | 2447 | size_norm: 0.08, |
| | 2448 | tracking: 1.0, |
| | 2449 | line_spacing: 1.0, |
| | 2450 | center: [0.5, 0.5], |
| | 2451 | h_lcr: 0.0, |
| | 2452 | v_tcb: 0.0, |
| | 2453 | fill_rgba: [1.0, 0.85, 0.7, 1.0], |
| | 2454 | write_on_start: 0.0, |
| | 2455 | write_on_end: 1.0, |
| | 2456 | shear_x: 0.0, |
| | 2457 | cls: &[], |
| | 2458 | outline_rgba: [0.1, 0.2, 0.3, 0.9], |
| | 2459 | outline_thickness_norm: 0.03, |
| | 2460 | outline_enabled: true, |
| | 2461 | soft_fill: [0.0; 3], |
| | 2462 | soft_outline: [0.0; 3], |
| | 2463 | baseline_at_center: false, |
| | 2464 | }; |
| | 2465 | let first = rasterize_text_plus_rich([960, 540], &p, 0); |
| | 2466 | let second = rasterize_text_plus_rich([960, 540], &p, 0); |
| | 2467 | assert_eq!(first, second, "cached glyph rasterization must be bit-identical"); |
| | 2468 | |
| | 2469 | let mut p_plain = p; |
| | 2470 | p_plain.outline_enabled = false; |
| | 2471 | let p1 = rasterize_text_plus_rich([960, 540], &p_plain, 0); |
| | 2472 | let p2 = rasterize_text_plus_rich([960, 540], &p_plain, 0); |
| | 2473 | assert_eq!(p1, p2, "u8 fast-path glyph rasterization must be bit-identical"); |
| | 2474 | |
| | 2475 | // Verify bounded eviction in GlyphCache. |
| | 2476 | let mut cache = GlyphCache::new(); |
| | 2477 | for i in 0..(MAX_GLYPH_CACHE_ENTRIES + 64) { |
| | 2478 | let key = GlyphCacheKey { |
| | 2479 | font_id: 999, |
| | 2480 | glyph_id: i as u16, |
| | 2481 | size_bits: 1000, |
| | 2482 | lean_bits: 0, |
| | 2483 | stroke_bits: 0, |
| | 2484 | sub_x_bits: 0, |
| | 2485 | sub_y_bits: 0, |
| | 2486 | }; |
| | 2487 | let entry = Arc::new(CachedGlyphCoverage { |
| | 2488 | fill: Some(Coverage { |
| | 2489 | left: 0, |
| | 2490 | top: 0, |
| | 2491 | width: 4, |
| | 2492 | height: 4, |
| | 2493 | data: vec![255; 16], |
| | 2494 | }), |
| | 2495 | stroke: None, |
| | 2496 | bytes: 16, |
| | 2497 | }); |
| | 2498 | cache.insert(key, entry); |
| | 2499 | } |
| | 2500 | assert!(cache.map.len() <= MAX_GLYPH_CACHE_ENTRIES); |
| | 2501 | assert!(cache.total_bytes <= MAX_GLYPH_CACHE_BYTES); |
| | 2502 | } |
| | 2503 | |
| | 2504 | #[test] |
| | 2505 | fn lazy_font_lookup_resolves_and_caches() { |
| | 2506 | let f1 = Font::find("Helvetica Neue", "Regular").expect("Helvetica Neue"); |
| | 2507 | let f2 = Font::find("Helvetica Neue", "Regular").expect("cached Helvetica Neue"); |
| | 2508 | assert_eq!(f1.id, f2.id); |
| | 2509 | let mut t_sum = std::time::Duration::ZERO; |
| | 2510 | for _ in 0..20 { |
| | 2511 | let t0 = std::time::Instant::now(); |
| | 2512 | let f = Font::find("Helvetica Neue", "Regular").unwrap(); |
| | 2513 | t_sum += t0.elapsed(); |
| | 2514 | assert_eq!(f.id, f1.id); |
| | 2515 | } |
| | 2516 | assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}"); |
| | 2517 | } |
| 1959 | } | 2518 | } |