Skip to main content

getfont/
getfont.rs

1//! Basic font query example (synchronous API)
2//!
3//! Demonstrates the classic `FcFontCache::build()` API which scans ALL system
4//! fonts upfront. This works but is slow (~700ms on a system with 1000 fonts).
5//! For faster startup, see the `registry` example.
6//!
7//! Run with:
8//!   cargo run --example getfont
9
10use rust_fontconfig::{FcFontCache, FcPattern, FcWeight};
11use std::time::Instant;
12
13fn main() {
14    // Build the cache — scans and parses ALL system fonts
15    let start = Instant::now();
16    let cache = FcFontCache::build();
17    let build_time = start.elapsed();
18
19    println!("Cache built: {} fonts in {:?}\n", cache.list().len(), build_time);
20
21    // Query various fonts to showcase fuzzy matching
22    let queries = [
23        ("Arial", FcWeight::Normal, "Common sans-serif"),
24        ("Helvetica", FcWeight::Bold, "Bold variant"),
25        ("Courier", FcWeight::Normal, "Monospace"),
26        ("Georgia", FcWeight::Normal, "Serif"),
27        ("sans-serif", FcWeight::Normal, "Generic family"),
28    ];
29
30    for (name, weight, desc) in &queries {
31        let t = Instant::now();
32        let result = cache.query(
33            &FcPattern {
34                name: Some(name.to_string()),
35                weight: *weight,
36                ..Default::default()
37            },
38            &mut Vec::new(),
39        );
40
41        match result {
42            Some(fm) => {
43                let found = cache
44                    .get_metadata_by_id(&fm.id)
45                    .and_then(|m| m.name.clone().or(m.family.clone()))
46                    .unwrap_or_else(|| format!("{:?}", fm.id));
47                println!(
48                    "  ✓ '{}' ({}) -> {} [{:?}]",
49                    name, desc, found, t.elapsed()
50                );
51            }
52            None => println!("  ✗ '{}' ({}) -> NOT FOUND [{:?}]", name, desc, t.elapsed()),
53        }
54    }
55}