typg_core/search.rs
1//! Font metadata extraction and search.
2//!
3//! This module opens font files, extracts searchable metadata from their
4//! OpenType tables, and evaluates that metadata against a [`Query`]. The same
5//! metadata model is used by live scans, cache files, and indexed search.
6//!
7//! One file may yield multiple results because collection formats such as TTC
8//! and OTC can store several faces in a single container.
9//!
10//! Made by FontLab <https://www.fontlab.com/>
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::mpsc::Sender;
14
15use anyhow::{Context, Result};
16use rayon::prelude::*;
17use rayon::ThreadPoolBuilder;
18use read_fonts::tables::name::NameId;
19use read_fonts::types::Tag;
20use read_fonts::{FontRef, TableProvider};
21use serde::{Deserialize, Serialize};
22use skrifa::{FontRef as SkrifaFontRef, MetadataProvider};
23
24use crate::discovery::{FontDiscovery, PathDiscovery};
25use crate::query::Query;
26use crate::tags::{tag4, tag_to_string};
27
28/// Everything we know about a single font face, extracted from its binary tables.
29///
30/// One font *file* may contain multiple faces (in a TTC/OTC collection), and
31/// each face gets its own `TypgFontFaceMeta`. This struct is the unit of
32/// comparison — every query filter is evaluated against one of these.
33///
34/// All tag vectors are sorted and deduplicated after extraction, so you can
35/// safely use set-intersection logic against them.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct TypgFontFaceMeta {
38 /// Human-readable names for this font face.
39 ///
40 /// Collected from the font's `name` table: family name ("Helvetica"),
41 /// typographic family name ("Helvetica Neue"), full name ("Helvetica Neue
42 /// Bold"), PostScript name ("HelveticaNeue-Bold"), and subfamily
43 /// ("Bold"). The file stem (e.g., "HelveticaNeue-Bold" from the filename)
44 /// is always appended as a fallback, because some fonts have empty or
45 /// broken name tables.
46 ///
47 /// Sorted, deduplicated, trimmed of whitespace.
48 pub names: Vec<String>,
49
50 /// Variation axis tags. Empty for static (non-variable) fonts.
51 ///
52 /// Common axes: `wght` (weight: 100=Thin, 400=Regular, 700=Bold, 900=Black),
53 /// `wdth` (width: 75=Condensed, 100=Normal, 125=Expanded),
54 /// `opsz` (optical size: adjusts stroke contrast for small/large rendering),
55 /// `ital` (italic: 0=Upright, 1=Italic),
56 /// `slnt` (slant: oblique angle in degrees).
57 ///
58 /// Read from the font's `fvar` (font variations) table.
59 #[serde(
60 serialize_with = "serialize_tags",
61 deserialize_with = "deserialize_tags"
62 )]
63 pub axis_tags: Vec<Tag>,
64
65 /// OpenType layout feature tags from GSUB and GPOS tables.
66 ///
67 /// These control typographic behavior: `liga` (standard ligatures — fi, fl
68 /// become single glyphs), `smcp` (small capitals), `onum` (oldstyle
69 /// numerals), `kern` (kerning — fine-tuned spacing between specific letter
70 /// pairs), `calt` (contextual alternates), `dlig` (discretionary ligatures).
71 ///
72 /// GSUB features handle glyph *substitution* (replacing one glyph with
73 /// another). GPOS features handle glyph *positioning* (adjusting placement).
74 /// Both are merged here because the query doesn't distinguish them.
75 #[serde(
76 serialize_with = "serialize_tags",
77 deserialize_with = "deserialize_tags"
78 )]
79 pub feature_tags: Vec<Tag>,
80
81 /// Script tags declaring which writing systems this font supports.
82 ///
83 /// Read from GSUB and GPOS script lists. Common values: `latn` (Latin),
84 /// `arab` (Arabic), `cyrl` (Cyrillic), `grek` (Greek), `hani` (CJK
85 /// ideographs), `deva` (Devanagari), `thai` (Thai).
86 ///
87 /// A font can render characters from a script's Unicode range without
88 /// declaring script support here — the script tag means the font has
89 /// *shaping rules* (substitutions, positioning) specifically for that
90 /// writing system.
91 #[serde(
92 serialize_with = "serialize_tags",
93 deserialize_with = "deserialize_tags"
94 )]
95 pub script_tags: Vec<Tag>,
96
97 /// Every top-level table present in the font file.
98 ///
99 /// Useful for structural queries: does this font have `CFF ` (PostScript
100 /// outlines) or `glyf` (TrueType outlines)? Does it have `SVG ` (color
101 /// SVG glyphs) or `COLR` (color layer glyphs)? Does it have `fvar`
102 /// (variable font axes)?
103 ///
104 /// Read directly from the font's table directory — the index at the
105 /// start of every OpenType file.
106 #[serde(
107 serialize_with = "serialize_tags",
108 deserialize_with = "deserialize_tags"
109 )]
110 pub table_tags: Vec<Tag>,
111
112 /// Unicode codepoints this font can render, from its `cmap` table.
113 ///
114 /// The `cmap` (character map) is the font's promise: "give me this
115 /// Unicode codepoint, I'll give you a glyph." If U+00F1 (ñ) is in
116 /// this list, the font has a glyph for it.
117 ///
118 /// Sorted and deduplicated. Can be large — a CJK font may cover
119 /// 20,000+ codepoints.
120 pub codepoints: Vec<char>,
121
122 /// Whether this font has an `fvar` table, making it a variable font.
123 ///
124 /// Variable fonts contain continuous design axes (weight, width, etc.)
125 /// instead of discrete named instances. A single variable font file can
126 /// replace an entire family of static fonts.
127 pub is_variable: bool,
128
129 /// OS/2 `usWeightClass` value. Indicates visual weight on a 1–1000 scale.
130 ///
131 /// Standard values: 100=Thin, 200=ExtraLight, 300=Light, 400=Regular,
132 /// 500=Medium, 600=SemiBold, 700=Bold, 800=ExtraBold, 900=Black.
133 /// `None` if the font has no OS/2 table (rare in modern fonts).
134 #[serde(default)]
135 pub weight_class: Option<u16>,
136
137 /// OS/2 `usWidthClass` value. Indicates visual width on a 1–9 scale.
138 ///
139 /// Values: 1=UltraCondensed, 2=ExtraCondensed, 3=Condensed,
140 /// 4=SemiCondensed, 5=Normal, 6=SemiExpanded, 7=Expanded,
141 /// 8=ExtraExpanded, 9=UltraExpanded.
142 /// `None` if the font has no OS/2 table.
143 #[serde(default)]
144 pub width_class: Option<u16>,
145
146 /// OS/2 `sFamilyClass` split into (major class, subclass).
147 ///
148 /// The major class groups fonts by general style: 0=No classification,
149 /// 1=Oldstyle Serifs, 2=Transitional Serifs, 3=Modern Serifs,
150 /// 4=Clarendon Serifs, 5=Slab Serifs, 7=Freeform Serifs,
151 /// 8=Sans Serif, 9=Ornamentals, 10=Scripts, 12=Symbolic.
152 ///
153 /// The subclass provides finer detail within each major class.
154 /// For example, within Sans Serif (8): 1=IBM Neo-Grotesque Gothic,
155 /// 2=Humanist, 3=Low-x Round Geometric, etc.
156 ///
157 /// `None` if the font has no OS/2 table.
158 #[serde(default)]
159 pub family_class: Option<(u8, u8)>,
160
161 /// Creator and provenance strings from the font's name table.
162 ///
163 /// Includes: copyright notice (name ID 0), trademark (7), manufacturer
164 /// (8), designer (9), description (10), vendor URL (11), designer URL
165 /// (12), license description (13), license URL (14).
166 ///
167 /// Useful for searching by foundry ("Adobe"), designer ("Matthew Carter"),
168 /// or license type ("OFL").
169 #[serde(default)]
170 pub creator_names: Vec<String>,
171
172 /// License-specific strings from the font's name table.
173 ///
174 /// A subset of creator info focused on licensing: copyright notice
175 /// (name ID 0), license description (13), license info URL (14).
176 ///
177 /// Useful for compliance checks: "show me all fonts with an SIL Open
178 /// Font License" or "find fonts with no license URL."
179 #[serde(default)]
180 pub license_names: Vec<String>,
181}
182
183/// Where a font face lives on disk.
184///
185/// For standalone `.ttf`/`.otf` files, the path is enough. For collection
186/// files (`.ttc`/`.otc`) that bundle multiple faces, the `ttc_index`
187/// identifies which face inside the collection this refers to.
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct TypgFontSource {
190 /// Filesystem path to the font file.
191 pub path: PathBuf,
192 /// Face index within a TTC/OTC collection file.
193 ///
194 /// `None` for single-face files (`.ttf`, `.otf`).
195 /// `Some(0)`, `Some(1)`, etc. for faces inside a collection.
196 /// For example, a `.ttc` containing "Arial" and "Arial Bold" would have
197 /// indices 0 and 1.
198 pub ttc_index: Option<u32>,
199}
200
201impl TypgFontSource {
202 /// Format as `path#index` for collection members, plain path otherwise.
203 ///
204 /// Examples: `/fonts/Noto.ttc#0`, `/fonts/Noto.ttc#1`, `/fonts/Arial.ttf`.
205 /// This notation is a common convention across font tools.
206 pub fn path_with_index(&self) -> String {
207 if let Some(idx) = self.ttc_index {
208 format!("{}#{idx}", self.path.display())
209 } else {
210 self.path.display().to_string()
211 }
212 }
213}
214
215/// A search result: one font face that matched the query.
216///
217/// Pairs the file location ([`TypgFontSource`]) with everything we extracted
218/// from the font's binary tables ([`TypgFontFaceMeta`]). This is the primary
219/// output type of the search engine — what you iterate over to display results,
220/// build caches, or pipe into downstream tools.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct TypgFontFaceMatch {
223 /// Where the font lives: file path and optional TTC/OTC face index.
224 pub source: TypgFontSource,
225 /// Metadata extracted from the font's internal tables.
226 pub metadata: TypgFontFaceMeta,
227}
228
229/// Controls how the search engine runs: parallelism and traversal behavior.
230#[derive(Debug, Default, Clone)]
231pub struct SearchOptions {
232 /// Follow symbolic links when walking directories.
233 ///
234 /// Off by default to avoid infinite loops from circular symlinks.
235 /// Turn on when your font directories contain symlinks to real font
236 /// folders (common on macOS and Linux).
237 pub follow_symlinks: bool,
238
239 /// Number of parallel worker threads for font parsing.
240 ///
241 /// `None` (the default) uses all available CPU cores via rayon's
242 /// default thread pool. Set to `Some(1)` for single-threaded
243 /// operation (useful for debugging or constrained environments).
244 pub jobs: Option<usize>,
245}
246
247/// Search directories for fonts matching a query. The main entry point.
248///
249/// Walks the given directories, opens every font file found, extracts
250/// metadata, filters against the query, and returns all matches sorted by
251/// path (then by TTC index within each path).
252///
253/// This function collects all results in memory before returning — use
254/// [`search_streaming`] if you want results delivered as they're found
255/// (better for CLI output where users want to see progress immediately).
256///
257/// Corrupt or unreadable font files are silently skipped. The search
258/// never fails because of a single bad file.
259pub fn search(
260 paths: &[PathBuf],
261 query: &Query,
262 opts: &SearchOptions,
263) -> Result<Vec<TypgFontFaceMatch>> {
264 let discovery = PathDiscovery::new(paths.iter().cloned()).follow_symlinks(opts.follow_symlinks);
265 let candidates = discovery.discover()?;
266
267 let run_search = || -> Vec<TypgFontFaceMatch> {
268 let mut matches: Vec<TypgFontFaceMatch> = candidates
269 .par_iter()
270 .flat_map_iter(|loc| match load_metadata(&loc.path) {
271 Ok(faces) => faces,
272 Err(_) => Vec::new(),
273 })
274 .filter(|face| query.matches(&face.metadata))
275 .collect();
276
277 sort_matches(&mut matches);
278 matches
279 };
280
281 let matches = if let Some(jobs) = opts.jobs {
282 let pool = ThreadPoolBuilder::new().num_threads(jobs).build()?;
283 pool.install(run_search)
284 } else {
285 run_search()
286 };
287
288 Ok(matches)
289}
290
291/// Search directories and stream results as they're discovered.
292///
293/// Unlike [`search`], this doesn't wait until all fonts are processed. Each
294/// match is sent through the channel (`tx`) the moment it's found. Results
295/// arrive in arbitrary order — whichever thread finishes parsing a font
296/// first sends its matches first.
297///
298/// Use this for line-oriented output (plain text, paths, NDJSON) where the
299/// user benefits from seeing results immediately. The CLI's default output
300/// mode uses streaming so results start appearing while the scan is still
301/// running.
302///
303/// The sender (`tx`) is cloned across worker threads via rayon's
304/// `for_each_with`. When all threads finish, every clone is dropped, which
305/// closes the channel — the receiver knows the search is complete.
306///
307/// Corrupt or unreadable font files are silently skipped.
308pub fn search_streaming(
309 paths: &[PathBuf],
310 query: &Query,
311 opts: &SearchOptions,
312 tx: Sender<TypgFontFaceMatch>,
313) -> Result<()> {
314 let discovery = PathDiscovery::new(paths.iter().cloned()).follow_symlinks(opts.follow_symlinks);
315 let candidates = discovery.discover()?;
316
317 let run_search = || {
318 candidates
319 .par_iter()
320 .for_each_with(tx, |tx, loc| match load_metadata(&loc.path) {
321 Ok(faces) => {
322 for face in faces {
323 if query.matches(&face.metadata) {
324 let _ = tx.send(face);
325 }
326 }
327 }
328 Err(_) => {}
329 });
330 };
331
332 if let Some(jobs) = opts.jobs {
333 let pool = ThreadPoolBuilder::new().num_threads(jobs).build()?;
334 pool.install(run_search);
335 } else {
336 run_search();
337 }
338
339 Ok(())
340}
341
342/// Filter pre-loaded font metadata against a query. No disk I/O.
343///
344/// Takes a slice of already-extracted font metadata (typically loaded from
345/// a JSON cache file) and returns only the entries matching the query.
346/// Results are sorted by path.
347///
348/// This is the fast path for repeated queries: pay the cost of scanning
349/// and extracting once (via [`search`] or the CLI's `cache add` command),
350/// save the results to a JSON file, then filter them in memory as many
351/// times as you like.
352pub fn filter_cached(entries: &[TypgFontFaceMatch], query: &Query) -> Vec<TypgFontFaceMatch> {
353 let mut matches: Vec<TypgFontFaceMatch> = entries
354 .iter()
355 .filter(|entry| query.matches(&entry.metadata))
356 .cloned()
357 .collect();
358
359 sort_matches(&mut matches);
360 matches
361}
362
363/// Read a font file and extract metadata for every face it contains.
364///
365/// A standalone `.ttf`/`.otf` file yields one `TypgFontFaceMatch`.
366/// A collection file (`.ttc`/`.otc`) yields one per face — a file with
367/// 12 faces produces 12 results.
368///
369/// Uses `read-fonts` for low-level table access (axes, features, scripts,
370/// tables, names, OS/2 classification) and `skrifa` for higher-level APIs
371/// (cmap/charmap iteration). Both crates come from Google's fontations
372/// project.
373fn load_metadata(path: &Path) -> Result<Vec<TypgFontFaceMatch>> {
374 let data = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
375 let mut metas = Vec::new();
376
377 for font in FontRef::fonts(&data) {
378 let font = font?;
379 let ttc_index = font.ttc_index();
380 let sfont = if let Some(idx) = ttc_index {
381 SkrifaFontRef::from_index(&data, idx)?
382 } else {
383 SkrifaFontRef::new(&data)?
384 };
385
386 let names = collect_names(&font);
387 let mut axis_tags = collect_axes(&font);
388 let mut feature_tags = collect_features(&font);
389 let mut script_tags = collect_scripts(&font);
390 let mut table_tags = collect_tables(&font);
391 let mut codepoints = collect_codepoints(&sfont);
392 let fvar_tag = Tag::new(b"fvar");
393 let is_variable = table_tags.contains(&fvar_tag);
394 let (weight_class, width_class, family_class) = collect_classification(&font);
395 let mut creator_names = collect_creator_names(&font);
396 let mut license_names = collect_license_names(&font);
397
398 dedup_tags(&mut axis_tags);
399 dedup_tags(&mut feature_tags);
400 dedup_tags(&mut script_tags);
401 dedup_tags(&mut table_tags);
402 dedup_codepoints(&mut codepoints);
403 creator_names.sort_unstable();
404 creator_names.dedup();
405 license_names.sort_unstable();
406 license_names.dedup();
407
408 metas.push(TypgFontFaceMatch {
409 source: TypgFontSource {
410 path: path.to_path_buf(),
411 ttc_index,
412 },
413 metadata: TypgFontFaceMeta {
414 names: dedup_names(names, path),
415 axis_tags,
416 feature_tags,
417 script_tags,
418 table_tags,
419 codepoints,
420 is_variable,
421 weight_class,
422 width_class,
423 family_class,
424 creator_names,
425 license_names,
426 },
427 });
428 }
429
430 Ok(metas)
431}
432
433/// List every top-level table tag in the font's table directory.
434///
435/// The table directory is the index at the start of every OpenType file.
436/// It maps four-character tags to byte offsets. Common tables: `glyf`
437/// (TrueType outlines), `CFF ` (PostScript outlines), `GSUB`, `GPOS`,
438/// `OS/2`, `name`, `cmap`, `head`, `fvar` (variable font axes).
439fn collect_tables(font: &FontRef) -> Vec<Tag> {
440 font.table_directory
441 .table_records()
442 .iter()
443 .map(|rec| rec.tag())
444 .collect()
445}
446
447/// Extract variation axis tags from the `fvar` table.
448///
449/// Returns an empty vec for static (non-variable) fonts. For variable fonts,
450/// returns tags like `wght`, `wdth`, `opsz`, `ital`, `slnt`, plus any
451/// custom axes the designer defined.
452fn collect_axes(font: &FontRef) -> Vec<Tag> {
453 if let Ok(fvar) = font.fvar() {
454 if let Ok(axes) = fvar.axes() {
455 return axes.iter().map(|axis| axis.axis_tag()).collect();
456 }
457 }
458 Vec::new()
459}
460
461/// Collect OpenType feature tags from GSUB and GPOS tables.
462///
463/// GSUB (glyph substitution) holds features like `liga` (ligatures), `smcp`
464/// (small caps), `calt` (contextual alternates). GPOS (glyph positioning)
465/// holds features like `kern` (kerning), `mark` (mark-to-base positioning).
466/// Both tables' feature lists are merged into one flat vec.
467fn collect_features(font: &FontRef) -> Vec<Tag> {
468 let mut tags = Vec::new();
469 if let Ok(gsub) = font.gsub() {
470 if let Ok(list) = gsub.feature_list() {
471 tags.extend(list.feature_records().iter().map(|rec| rec.feature_tag()));
472 }
473 }
474 if let Ok(gpos) = font.gpos() {
475 if let Ok(list) = gpos.feature_list() {
476 tags.extend(list.feature_records().iter().map(|rec| rec.feature_tag()));
477 }
478 }
479 tags
480}
481
482/// Collect script tags from GSUB and GPOS tables.
483///
484/// Script tags identify writing systems: `latn` (Latin), `arab` (Arabic),
485/// `cyrl` (Cyrillic), `hani` (CJK ideographs), `deva` (Devanagari).
486/// A font declares script support when it has shaping rules (lookups)
487/// specifically written for that script's typographic conventions.
488fn collect_scripts(font: &FontRef) -> Vec<Tag> {
489 let mut tags = Vec::new();
490 if let Ok(gsub) = font.gsub() {
491 if let Ok(list) = gsub.script_list() {
492 tags.extend(list.script_records().iter().map(|rec| rec.script_tag()));
493 }
494 }
495 if let Ok(gpos) = font.gpos() {
496 if let Ok(list) = gpos.script_list() {
497 tags.extend(list.script_records().iter().map(|rec| rec.script_tag()));
498 }
499 }
500 tags
501}
502
503/// Extract all Unicode codepoints from the font's `cmap` table.
504///
505/// The `cmap` (character map) maps Unicode codepoints to glyph IDs. If a
506/// codepoint appears here, the font has a glyph for it. We use `skrifa`'s
507/// `charmap().mappings()` iterator, which walks every (codepoint, glyph_id)
508/// pair in the font's best available cmap subtable.
509///
510/// Invalid Unicode scalar values (surrogates, out-of-range) are silently
511/// skipped via `char::from_u32`.
512fn collect_codepoints(font: &SkrifaFontRef) -> Vec<char> {
513 let mut cps = Vec::new();
514 for (cp, _) in font.charmap().mappings() {
515 if let Some(ch) = char::from_u32(cp) {
516 cps.push(ch);
517 }
518 }
519 cps
520}
521
522/// Extract identifying name strings from the font's `name` table.
523///
524/// The `name` table stores human-readable strings in multiple languages and
525/// encodings. We read only Unicode-encoded records for these name IDs:
526///
527/// - **Family Name** (ID 1): e.g., "Helvetica Neue"
528/// - **Typographic Family Name** (ID 16): preferred family grouping
529/// - **Subfamily Name** (ID 2): e.g., "Bold Italic"
530/// - **Typographic Subfamily Name** (ID 17): preferred style name
531/// - **Full Name** (ID 4): e.g., "Helvetica Neue Bold Italic"
532/// - **PostScript Name** (ID 6): e.g., "HelveticaNeue-BoldItalic"
533///
534/// Non-Unicode records (legacy Mac Roman, Windows symbol) are skipped.
535/// Empty or whitespace-only strings are discarded.
536fn collect_names(font: &FontRef) -> Vec<String> {
537 let mut names = Vec::new();
538
539 if let Ok(name_table) = font.name() {
540 let data = name_table.string_data();
541 let wanted = [
542 NameId::FAMILY_NAME,
543 NameId::TYPOGRAPHIC_FAMILY_NAME,
544 NameId::SUBFAMILY_NAME,
545 NameId::TYPOGRAPHIC_SUBFAMILY_NAME,
546 NameId::FULL_NAME,
547 NameId::POSTSCRIPT_NAME,
548 ];
549
550 for record in name_table.name_record() {
551 if !record.is_unicode() {
552 continue;
553 }
554 if !wanted.contains(&record.name_id()) {
555 continue;
556 }
557 if let Ok(entry) = record.string(data) {
558 let rendered = entry.to_string();
559 if !rendered.trim().is_empty() {
560 names.push(rendered);
561 }
562 }
563 }
564 }
565
566 names
567}
568
569/// Extract creator and provenance strings from the `name` table.
570///
571/// Covers a broad range of attribution fields: copyright notice (ID 0),
572/// trademark (7), manufacturer/foundry (8), designer (9), description (10),
573/// vendor URL (11), designer URL (12), license description (13), license
574/// info URL (14). These let users search by foundry, designer, or license.
575fn collect_creator_names(font: &FontRef) -> Vec<String> {
576 let mut names = Vec::new();
577
578 if let Ok(name_table) = font.name() {
579 let data = name_table.string_data();
580 let wanted = [
581 NameId::COPYRIGHT_NOTICE,
582 NameId::TRADEMARK,
583 NameId::MANUFACTURER,
584 NameId::DESIGNER,
585 NameId::DESCRIPTION,
586 NameId::VENDOR_URL,
587 NameId::DESIGNER_URL,
588 NameId::LICENSE_DESCRIPTION,
589 NameId::LICENSE_URL,
590 ];
591
592 for record in name_table.name_record() {
593 if !record.is_unicode() {
594 continue;
595 }
596 if !wanted.contains(&record.name_id()) {
597 continue;
598 }
599 if let Ok(entry) = record.string(data) {
600 let rendered = entry.to_string();
601 if !rendered.trim().is_empty() {
602 names.push(rendered);
603 }
604 }
605 }
606 }
607
608 names
609}
610
611/// Extract license-specific strings from the `name` table.
612///
613/// A focused subset of creator info: copyright (ID 0), license description
614/// (13), and license URL (14). Separated from the broader creator fields
615/// so callers can search specifically by license terms.
616fn collect_license_names(font: &FontRef) -> Vec<String> {
617 let mut names = Vec::new();
618
619 if let Ok(name_table) = font.name() {
620 let data = name_table.string_data();
621 let wanted = [
622 NameId::COPYRIGHT_NOTICE,
623 NameId::LICENSE_DESCRIPTION,
624 NameId::LICENSE_URL,
625 ];
626
627 for record in name_table.name_record() {
628 if !record.is_unicode() {
629 continue;
630 }
631 if !wanted.contains(&record.name_id()) {
632 continue;
633 }
634 if let Ok(entry) = record.string(data) {
635 let rendered = entry.to_string();
636 if !rendered.trim().is_empty() {
637 names.push(rendered);
638 }
639 }
640 }
641 }
642
643 names
644}
645
646/// Extract weight class, width class, and family class from the OS/2 table.
647///
648/// The OS/2 table (named after IBM's OS/2 operating system — the name
649/// outlived the OS by decades) carries font classification metadata:
650///
651/// - `usWeightClass`: visual weight, 100 (Thin) to 900 (Black).
652/// - `usWidthClass`: visual width, 1 (UltraCondensed) to 9 (UltraExpanded).
653/// - `sFamilyClass`: a 16-bit value where the high byte is the major class
654/// (e.g., 8 = Sans Serif) and the low byte is the subclass (e.g., 1 =
655/// IBM Neo-Grotesque Gothic). We split it into `(major, subclass)`.
656///
657/// Returns `(None, None, None)` if the font lacks an OS/2 table (very rare
658/// in modern fonts, but possible in legacy or stripped files).
659fn collect_classification(font: &FontRef) -> (Option<u16>, Option<u16>, Option<(u8, u8)>) {
660 match font.os2() {
661 Ok(table) => {
662 let raw_family = table.s_family_class() as u16;
663 let class = (raw_family >> 8) as u8;
664 let subclass = (raw_family & 0x00FF) as u8;
665 (
666 Some(table.us_weight_class()),
667 Some(table.us_width_class()),
668 Some((class, subclass)),
669 )
670 }
671 Err(_) => (None, None, None),
672 }
673}
674
675/// Sort results by file path, then by TTC index within each file.
676/// Produces deterministic output regardless of thread scheduling order.
677fn sort_matches(matches: &mut [TypgFontFaceMatch]) {
678 matches.sort_by(|a, b| {
679 a.source
680 .path
681 .cmp(&b.source.path)
682 .then_with(|| a.source.ttc_index.cmp(&b.source.ttc_index))
683 });
684}
685
686fn dedup_tags(tags: &mut Vec<Tag>) {
687 tags.sort_unstable();
688 tags.dedup();
689}
690
691fn dedup_codepoints(codepoints: &mut Vec<char>) {
692 codepoints.sort_unstable();
693 codepoints.dedup();
694}
695
696/// Deduplicate name strings and add a filename-based fallback.
697///
698/// The file stem (e.g., "HelveticaNeue-Bold" from "HelveticaNeue-Bold.otf")
699/// is always appended. This ensures every font has at least one searchable
700/// name, even if its `name` table is empty or broken.
701fn dedup_names(mut names: Vec<String>, path: &Path) -> Vec<String> {
702 names.push(
703 path.file_stem()
704 .map(|s| s.to_string_lossy().to_string())
705 .unwrap_or_else(|| path.display().to_string()),
706 );
707
708 for name in names.iter_mut() {
709 *name = name.trim().to_string();
710 }
711
712 names.retain(|n| !n.is_empty());
713 names.sort_unstable();
714 names.dedup();
715 names
716}
717
718/// Serialize OpenType tags as human-readable strings in JSON.
719///
720/// Tags are stored as binary `Tag` values internally, but serialized as
721/// four-character strings (`"wght"`, `"liga"`) for readability in JSON
722/// output and cache files.
723fn serialize_tags<S>(tags: &[Tag], serializer: S) -> Result<S::Ok, S::Error>
724where
725 S: serde::Serializer,
726{
727 let as_strings: Vec<String> = tags.iter().copied().map(tag_to_string).collect();
728 as_strings.serialize(serializer)
729}
730
731/// Deserialize OpenType tags from their string representation back to `Tag` values.
732fn deserialize_tags<'de, D>(deserializer: D) -> Result<Vec<Tag>, D::Error>
733where
734 D: serde::Deserializer<'de>,
735{
736 let raw: Vec<String> = Vec::<String>::deserialize(deserializer)?;
737 raw.into_iter()
738 .map(|s| tag4(&s).map_err(serde::de::Error::custom))
739 .collect()
740}
741
742#[cfg(test)]
743mod tests {
744 use super::*;
745
746 #[test]
747 fn dedup_names_adds_fallback_and_trims() {
748 let names = vec![" Alpha ".to_string(), "Alpha".to_string()];
749 let path = Path::new("/fonts/Beta.ttf");
750 let deduped = dedup_names(names, path);
751
752 assert!(
753 deduped.contains(&"Alpha".to_string()),
754 "original names should be trimmed and kept"
755 );
756 assert!(
757 deduped.contains(&"Beta".to_string()),
758 "file stem should be added as fallback name"
759 );
760 assert_eq!(
761 deduped.len(),
762 2,
763 "dedup should remove duplicate entries and empty strings"
764 );
765 }
766
767 #[test]
768 fn dedup_tags_sorts_and_dedups() {
769 let mut tags = vec![
770 tag4("wght").unwrap(),
771 tag4("wght").unwrap(),
772 tag4("GSUB").unwrap(),
773 ];
774 dedup_tags(&mut tags);
775
776 assert_eq!(tags, vec![tag4("GSUB").unwrap(), tag4("wght").unwrap()]);
777 }
778
779 #[test]
780 fn dedup_codepoints_sorts_and_dedups() {
781 let mut cps = vec!['b', 'a', 'b'];
782 dedup_codepoints(&mut cps);
783 assert_eq!(cps, vec!['a', 'b']);
784 }
785}