Skip to main content

frus_text/
lib.rs

1//! `frus-text` — text measurement, and in time shaping, on top of
2//! [`cosmic_text`](https://docs.rs/cosmic-text).
3//!
4//! At this milestone the API is limited to [`measure`]: the natural size of a line
5//! of text, which the layout engine needs in order to size a `Text` widget.
6//!
7//! The `FontSystem`, which loads the fonts, is expensive: it is initialised
8//! **lazily** and shared behind a `Mutex`. That is a pragmatic v1 choice;
9//! unifying it with the renderer's own `FontSystem` will come later.
10
11#![deny(missing_docs)]
12
13// The README's example is compiled and run by `cargo test --doc`, so it cannot rot.
14#[cfg(doctest)]
15#[doc = include_str!("../README.md")]
16pub struct ReadmeDoctests;
17
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::{Mutex, OnceLock, RwLock};
20
21use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping, Style, Weight};
22use frus_core::{fits, FontWeight, Point, Rect, ResolvedTextStyle, Size, TextRun, TextStyle};
23
24/// The default line-height to font-size ratio.
25///
26/// It lives in `frus-core` now, because the renderer needs the same number and a copy of
27/// it here is a copy that can drift: a measure and a paint disagreeing about how tall a
28/// line is puts the second line of every paragraph where the layout reserved nothing.
29use frus_core::DEFAULT_LINE_HEIGHT as LINE_HEIGHT_FACTOR;
30
31// --- The bundled fonts ---
32//
33// Bundling guarantees deterministic text on **every** platform — Android above all,
34// where the system "sans-serif" alias, defined in `fonts.xml` and not read by fontdb,
35// resolves to no font at all.
36//
37// It is also the single largest thing frus puts in an application: about 3.4 MB of
38// faces, ~1.8 MB once the APK compresses them, which is roughly **40%** of a minimal
39// frus app (milestone 292). So each group is a cargo feature, on by default, and an
40// application that ships its own faces can turn off the ones it does not need:
41//
42// ```toml
43// frus = { version = "0.3", default-features = false, features = ["bundled-sans"] }
44// ```
45//
46// Turning one off never turns an API into a panic — see [`available_style`] and
47// [`family_for`], which resolve to what is actually loaded.
48
49/// The bundled sans-serif, regular and bold. cosmic-text demands an **exact** weight
50/// match on the primary family, so both are needed for `.bold()` to shape rather than
51/// fall through to platform lists that do not exist on Android.
52#[cfg(feature = "bundled-sans")]
53const DEJAVU_SANS: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
54#[cfg(feature = "bundled-sans")]
55const DEJAVU_SANS_BOLD: &[u8] = include_bytes!("../assets/DejaVuSans-Bold.ttf");
56/// The **oblique** faces, for the same reason one step further: cosmic-text demands an
57/// exact *style* match too, so without them a plain `.italic()` used to **panic** ("no
58/// default font found") — caught on the Android device. They are 1.28 MB of the 3.4,
59/// so they are separable; when they are absent italic text is rendered **upright**
60/// rather than not at all.
61#[cfg(feature = "bundled-italic")]
62const DEJAVU_SANS_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-Oblique.ttf");
63#[cfg(feature = "bundled-italic")]
64const DEJAVU_SANS_BOLD_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-BoldOblique.ttf");
65/// The monospace face — only ever reached by widgets that ask for it (`Kbd`, code).
66#[cfg(feature = "bundled-mono")]
67const DEJAVU_MONO: &[u8] = include_bytes!("../assets/DejaVuSansMono.ttf");
68/// **Arabic** (Noto Naskh): DejaVu does not cover the Arabic script — it has no
69/// contextual joining forms — so this face provides the fallback for Arabic runs.
70#[cfg(feature = "bundled-arabic")]
71const NOTO_ARABIC: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Regular.ttf");
72#[cfg(feature = "bundled-arabic")]
73const NOTO_ARABIC_BOLD: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Bold.ttf");
74
75/// The bundled fonts' internal family names; they must match the TTFs.
76#[cfg(feature = "bundled-sans")]
77const SANS_FAMILY: &str = "DejaVu Sans";
78#[cfg(feature = "bundled-mono")]
79const MONO_FAMILY: &str = "DejaVu Sans Mono";
80/// The bundled Arabic face's family (Noto Naskh).
81#[cfg(feature = "bundled-arabic")]
82const ARABIC_FAMILY: &str = "Noto Naskh Arabic";
83
84// --- The families text actually resolves to ---
85//
86// `None` means "nothing is loaded for this role": text falls back to the generic
87// family and lets the platform answer, which is the best that can be done and is what
88// the desktop wants anyway. An application that ships its own faces names them here
89// through [`set_default_family`] / [`set_monospace_family`].
90//
91// A slot holds the name **as it was asked for**. What it is drawn in is decided against
92// the faces actually loaded — see [`loaded_family`] — because the name a developer writes
93// and the name inside a font file are often not the same: Inter's static files call their
94// family "Inter 24pt". A family nobody loaded is not a smaller failure on Android, where
95// there is no fallback list behind it: it draws **nothing at all** (milestone 626).
96
97#[cfg(feature = "bundled-sans")]
98static SANS: RwLock<Option<&'static str>> = RwLock::new(Some(SANS_FAMILY));
99#[cfg(not(feature = "bundled-sans"))]
100static SANS: RwLock<Option<&'static str>> = RwLock::new(None);
101#[cfg(feature = "bundled-mono")]
102static MONO: RwLock<Option<&'static str>> = RwLock::new(Some(MONO_FAMILY));
103#[cfg(not(feature = "bundled-mono"))]
104static MONO: RwLock<Option<&'static str>> = RwLock::new(None);
105#[cfg(feature = "bundled-arabic")]
106static ARABIC: RwLock<Option<&'static str>> = RwLock::new(Some(ARABIC_FAMILY));
107#[cfg(not(feature = "bundled-arabic"))]
108static ARABIC: RwLock<Option<&'static str>> = RwLock::new(None);
109/// Whether an italic face exists for the default family. Set when the font system is
110/// built, by looking at what was actually loaded rather than at what was asked for.
111static ITALIC: AtomicBool = AtomicBool::new(cfg!(feature = "bundled-italic"));
112
113/// Faces the application supplies itself. Every `FontSystem` frus builds loads them,
114/// so they must be registered **before the application runs** — the renderer builds
115/// its own system at start-up, exactly like declaring fonts in a manifest.
116static EXTRA_FONTS: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
117
118/// The families inside [`EXTRA_FONTS`], in the order they were registered: the first
119/// place to look when a name the application gave matches nothing.
120static APP_FAMILIES: Mutex<Vec<String>> = Mutex::new(Vec::new());
121
122/// Registers a font face from its bytes (TTF/OTF), for the whole process.
123///
124/// Call it **before** starting the application: the renderer builds its font database
125/// at start-up and a face added afterwards will measure but not paint.
126///
127/// ```ignore
128/// frus_text::add_font(include_bytes!("../fonts/Inter-Regular.ttf").to_vec());
129/// frus_text::set_default_family("Inter");
130/// ```
131///
132/// Bytes that hold no face this build can read are not registered, and the console says
133/// so: a file that is not a font, or not the one you meant, is otherwise found on a device.
134pub fn add_font(data: Vec<u8>) {
135    let families = families_in(&data);
136    if families.is_empty() {
137        log::warn!(
138            "frus: add_font was given {} bytes that hold no font face; nothing was registered",
139            data.len()
140        );
141        return;
142    }
143    {
144        let mut known = APP_FAMILIES.lock().expect("font registry");
145        for family in families {
146            if !known.contains(&family) {
147                known.push(family);
148            }
149        }
150    }
151    EXTRA_FONTS
152        .lock()
153        .expect("font registry")
154        .push(data.clone());
155    // Anything already measuring gets it too, so tests and tools do not have to care
156    // about ordering.
157    if let Some(system) = FONT_SYSTEM.get() {
158        if let Ok(mut system) = system.lock() {
159            let db = system.db_mut();
160            db.load_font_data(data);
161            take_stock(db);
162        }
163    }
164    forget_measurements();
165}
166
167/// Names the family text uses by default — the one an application ships instead of,
168/// or alongside, the bundled sans. The face itself must be registered with
169/// [`add_font`], or be present on the system.
170///
171/// The name is the one **inside** the font file, which is not always the file's: Inter's
172/// static files are called "Inter 24pt". A name that matches no loaded family is not left
173/// to draw nothing. frus takes the loaded family it plainly means — the same name in
174/// another case or spacing, or one that extends it by a word ("Inter" → "Inter 24pt") —
175/// and failing that the first family the application registered, then the platform's own
176/// sans. The console names what was chosen and what to write instead.
177pub fn set_default_family(name: &'static str) {
178    *SANS.write().expect("family registry") = Some(name);
179    forget_measurements();
180}
181
182/// Names the family monospaced text uses. See [`set_default_family`], whose rules for a
183/// name that is not loaded apply here too; with nothing to fall back on, monospaced text
184/// is drawn in the default family rather than not at all.
185pub fn set_monospace_family(name: &'static str) {
186    *MONO.write().expect("family registry") = Some(name);
187    forget_measurements();
188}
189
190/// The family names a font file declares, in the form fontdb reports them (the
191/// typographic family when the file has one).
192fn families_in(data: &[u8]) -> Vec<String> {
193    let mut db = cosmic_text::fontdb::Database::new();
194    db.load_font_data(data.to_vec());
195    let mut names: Vec<String> = Vec::new();
196    for face in db.faces() {
197        for (name, _) in &face.families {
198            if !names.contains(name) {
199                names.push(name.clone());
200            }
201        }
202    }
203    names
204}
205
206/// A family name with case, spaces, hyphens and underscores taken out: "Open Sans",
207/// "open-sans" and "OpenSans" are one name to a person, and three to an exact match.
208fn squashed(name: &str) -> String {
209    name.chars()
210        .filter(|c| !matches!(c, ' ' | '-' | '_'))
211        .flat_map(char::to_lowercase)
212        .collect()
213}
214
215/// The loaded family `requested` means, or `None` when none plainly does.
216///
217/// Three tries, from the strictest: the name exactly; the name up to case, spaces and
218/// hyphens; a family that **extends** it by a word — "Inter" finds "Inter 24pt", which is
219/// what Inter's static files call themselves. Among several extensions the ones in
220/// `preferred` (the application's own faces) come first, then the shortest, so "DejaVu"
221/// finds "DejaVu Sans" before "DejaVu Sans Mono".
222///
223/// It never guesses past that. A name that merely shares a first letter, or that the
224/// loaded family only begins ("Inter Tight" asked, "Inter" loaded), is not a match: a
225/// wrong face drawn silently is the failure this exists to end, not a new one.
226fn match_family<'a>(
227    requested: &str,
228    loaded: &'a [String],
229    preferred: &[String],
230) -> Option<&'a str> {
231    if let Some(exact) = loaded.iter().find(|family| *family == requested) {
232        return Some(exact);
233    }
234    let wanted = squashed(requested);
235    if let Some(same) = loaded.iter().find(|family| squashed(family) == wanted) {
236        return Some(same);
237    }
238    let prefix = format!("{} ", requested.trim().to_lowercase());
239    loaded
240        .iter()
241        .filter(|family| family.to_lowercase().starts_with(&prefix))
242        .min_by_key(|family| (!preferred.contains(family), family.len()))
243        .map(String::as_str)
244}
245
246/// The weights a face covers: one, or the range of its `wght` axis for a variable font,
247/// which draws every weight in between.
248fn weight_range(
249    db: &cosmic_text::fontdb::Database,
250    face: &cosmic_text::fontdb::FaceInfo,
251) -> (u16, u16) {
252    use cosmic_text::skrifa::MetadataProvider;
253    let axis = db.with_face_data(face.id, |data, index| {
254        let font = cosmic_text::skrifa::FontRef::from_index(data, index).ok()?;
255        let axis = font
256            .axes()
257            .get_by_tag(cosmic_text::skrifa::Tag::new(b"wght"))?;
258        Some((axis.min_value() as u16, axis.max_value() as u16))
259    });
260    match axis {
261        Some(Some((low, high))) if low <= high => (low, high),
262        _ => (face.weight.0, face.weight.0),
263    }
264}
265
266/// What the font database holds, as far as naming a family goes. Every `FontSystem` frus
267/// builds loads the same faces, so one inventory answers for all of them.
268struct Loaded {
269    /// Every family, as the files spell it.
270    families: Vec<String>,
271    /// The families that can draw text — every one but the emoji faces.
272    text: Vec<String>,
273    /// The application's own families, in registration order.
274    app: Vec<String>,
275    /// The families with an oblique or italic face.
276    slanted: Vec<String>,
277    /// Whether the generic sans-serif and monospace resolved to a face before frus
278    /// pointed them anywhere: on a desktop they do, on Android nothing answers.
279    generic_sans: bool,
280    generic_mono: bool,
281    /// What [`loaded_family`] answered, per name asked. An inventory is replaced whenever
282    /// a face arrives, and its answers go with it.
283    answers: Mutex<std::collections::HashMap<&'static str, Option<&'static str>>>,
284}
285
286impl Loaded {
287    fn of(db: &cosmic_text::fontdb::Database) -> Self {
288        use cosmic_text::fontdb::{Family, Query, Style};
289        let mut families: Vec<String> = Vec::new();
290        let mut text: Vec<String> = Vec::new();
291        let mut slanted: Vec<String> = Vec::new();
292        for face in db.faces() {
293            let emoji = face.post_script_name.contains("Emoji");
294            for (name, _) in &face.families {
295                if !families.contains(name) {
296                    families.push(name.clone());
297                }
298                if !emoji && !text.contains(name) {
299                    text.push(name.clone());
300                }
301                if face.style != Style::Normal && !slanted.contains(name) {
302                    slanted.push(name.clone());
303                }
304            }
305        }
306        let resolves = |family| {
307            db.query(&Query {
308                families: &[family],
309                ..Query::default()
310            })
311            .is_some()
312        };
313        Loaded {
314            families,
315            text,
316            app: APP_FAMILIES.lock().expect("font registry").clone(),
317            slanted,
318            generic_sans: resolves(Family::SansSerif),
319            generic_mono: resolves(Family::Monospace),
320            answers: Mutex::new(std::collections::HashMap::new()),
321        }
322    }
323
324    /// What text is drawn in when the family asked for is not loaded: the application's
325    /// first face, then the platform's sans (Roboto, on Android), then any face that draws
326    /// text — never nothing while there is something.
327    fn fallback(&self) -> Option<&str> {
328        self.app
329            .iter()
330            .find(|family| self.text.contains(family))
331            .or_else(|| self.text.iter().find(|family| *family == PLATFORM_SANS))
332            .or_else(|| self.text.first())
333            .map(String::as_str)
334    }
335
336    /// Whether default text has nothing good to be drawn in: the family asked for is not
337    /// there, nor any face of the application's, nor a generic sans the platform answers
338    /// for. Only Android gets here with a build that dropped `bundled-sans`, and it is
339    /// the cue to take the platform's own sans from disk.
340    #[cfg(any(target_os = "android", test))]
341    fn wants_platform_sans(&self, requested: Option<&str>) -> bool {
342        let named = requested.is_some_and(|name| {
343            match_family(name, &self.families, &self.app)
344                .is_some_and(|family| self.text.iter().any(|text| text == family))
345        });
346        let own = self.app.iter().any(|family| self.text.contains(family));
347        !(named || own || (requested.is_none() && self.generic_sans))
348    }
349}
350
351/// The weights the default family covers, as ranges — one weight for a static face, the
352/// span of its `wght` axis for a variable one. Empty when the default family is the
353/// platform's generic, which is not frus's to inventory.
354static WEIGHTS: RwLock<Vec<(u16, u16)>> = RwLock::new(Vec::new());
355
356/// The weight ranges `family`'s faces cover in `db`, upright faces first: an italic-only
357/// family still has weights to offer.
358fn weights_of(db: &cosmic_text::fontdb::Database, family: &str) -> Vec<(u16, u16)> {
359    let faces: Vec<_> = db
360        .faces()
361        .filter(|face| face.families.iter().any(|(name, _)| name == family))
362        .collect();
363    let upright: Vec<_> = faces
364        .iter()
365        .filter(|face| face.style == cosmic_text::fontdb::Style::Normal)
366        .collect();
367    let chosen = if upright.is_empty() {
368        faces.iter().collect()
369    } else {
370        upright
371    };
372    let mut ranges: Vec<(u16, u16)> = chosen.iter().map(|face| weight_range(db, face)).collect();
373    ranges.sort_unstable();
374    ranges.dedup();
375    ranges
376}
377
378/// The weight to ask for when `wanted` is asked of a family covering `have`, by the rule
379/// type on the web follows: an exact weight, or one inside a variable face's range, as it
380/// is; for 400 to 500, the next heavier up to 500, then lighter, then heavier; below 400,
381/// lighter first; above 500, heavier first. `have` empty answers `wanted`.
382fn nearest_weight(wanted: u16, have: &[(u16, u16)]) -> u16 {
383    if have
384        .iter()
385        .any(|&(low, high)| (low..=high).contains(&wanted))
386    {
387        return wanted;
388    }
389    // Outside every range, the candidates are the ranges' ends.
390    let mut ends: Vec<u16> = have.iter().flat_map(|&(low, high)| [low, high]).collect();
391    ends.sort_unstable();
392    ends.dedup();
393    let lighter = ends.iter().rev().find(|&&w| w < wanted).copied();
394    let heavier = ends.iter().find(|&&w| w > wanted).copied();
395    let pick = if (400..=500).contains(&wanted) {
396        ends.iter()
397            .find(|&&w| w > wanted && w <= 500)
398            .copied()
399            .or(lighter)
400            .or(heavier)
401    } else if wanted < 400 {
402        lighter.or(heavier)
403    } else {
404        heavier.or(lighter)
405    };
406    pick.unwrap_or(wanted)
407}
408
409/// The family Android draws its own text in, and the one frus takes from the platform
410/// when nothing else can draw.
411const PLATFORM_SANS: &str = "Roboto";
412
413/// The inventory of the last font database frus built. `None` until one is built — and
414/// then nothing can be judged, and names are taken as written.
415static LOADED: RwLock<Option<Loaded>> = RwLock::new(None);
416
417/// Family names the inventory gave out. The slots hold `&'static str`, and a name read
418/// from a font file is not one; each is leaked once, and only once.
419static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
420
421fn interned(name: &str) -> &'static str {
422    let mut interned = INTERNED.lock().expect("family registry");
423    if let Some(found) = interned.iter().find(|known| **known == name) {
424        return found;
425    }
426    let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());
427    interned.push(leaked);
428    leaked
429}
430
431/// What the console has already been told. A warning a frame would print sixty times a
432/// second is noise; once is the message.
433static WARNED: Mutex<Vec<String>> = Mutex::new(Vec::new());
434
435fn warn_once(message: String) {
436    let mut warned = WARNED.lock().expect("family registry");
437    if !warned.contains(&message) {
438        log::warn!("{message}");
439        warned.push(message);
440    }
441}
442
443/// Takes the inventory of `db` and points its generic families at faces that are there.
444/// Run whenever the faces change: a family's weights, its italic and the names it answers
445/// to are all read from it.
446fn take_stock(db: &mut cosmic_text::fontdb::Database) {
447    *LOADED.write().expect("family registry") = Some(Loaded::of(db));
448    // Makes every generic family resolve to a font that is actually present — but
449    // only when one is: pointing `sans-serif` at a family nobody loaded is worse than
450    // leaving fontdb's own answer alone.
451    let sans = default_family();
452    if let Some(sans) = sans {
453        db.set_sans_serif_family(sans);
454        db.set_serif_family(sans);
455        db.set_cursive_family(sans);
456        db.set_fantasy_family(sans);
457    }
458    if let cosmic_text::Family::Name(mono) = monospace_family() {
459        db.set_monospace_family(mono);
460    }
461    *WEIGHTS.write().expect("family registry") = match sans {
462        Some(name) => weights_of(db, name),
463        None => Vec::new(),
464    };
465    // What is *actually* there decides whether italic is asked for, since an
466    // application may have supplied an oblique face of its own — or none.
467    let italic = match LOADED.read().expect("family registry").as_ref() {
468        Some(loaded) => match sans {
469            Some(name) => loaded.slanted.iter().any(|family| family == name),
470            None => !loaded.slanted.is_empty(),
471        },
472        None => false,
473    };
474    ITALIC.store(italic, Ordering::Relaxed);
475}
476
477/// The loaded family `name` means — itself when a face carries it, otherwise what
478/// [`match_family`] finds, with a warning naming it — or `None` when nothing loaded
479/// answers to it. Before any font database exists there is nothing to judge against, and
480/// the name is taken as written.
481fn loaded_family(name: &'static str) -> Option<&'static str> {
482    let guard = LOADED.read().expect("family registry");
483    let Some(loaded) = guard.as_ref() else {
484        return Some(name);
485    };
486    let mut answers = loaded.answers.lock().expect("family registry");
487    if let Some(answer) = answers.get(name) {
488        return *answer;
489    }
490    let answer = match_family(name, &loaded.families, &loaded.app).map(interned);
491    if let Some(actual) = answer {
492        if actual != name {
493            warn_once(format!(
494                "frus: no font family is called \"{name}\"; drawing \"{actual}\", the name \
495                 inside the font files. Write \"{actual}\" to say so."
496            ));
497        }
498    }
499    answers.insert(name, answer);
500    answer
501}
502
503/// The family to draw in when `name`, asked for in the role `role`, is not loaded — with
504/// a warning that says so and lists what the application did register.
505fn fallback_for(role: &str, name: &str) -> Option<&'static str> {
506    let guard = LOADED.read().expect("family registry");
507    let loaded = guard.as_ref()?;
508    let fallback = loaded.fallback().map(interned);
509    let registered = if loaded.app.is_empty() {
510        "add_font registered none".to_string()
511    } else {
512        format!("add_font registered {:?}", loaded.app)
513    };
514    let drawn = match fallback {
515        Some(family) => format!("drawing \"{family}\" instead"),
516        None => "and no other face can draw text".to_string(),
517    };
518    warn_once(format!(
519        "frus: the {role} font family \"{name}\" is not loaded; {drawn}. The name must be \
520         the one inside the font file ({registered})."
521    ));
522    fallback
523}
524
525/// The family default text is drawn in: the one the application named, as it is loaded;
526/// failing that a face that can draw, never a name that resolves to nothing. `None` leaves
527/// the generic sans-serif to the platform, which answers on a desktop.
528fn default_family() -> Option<&'static str> {
529    let requested = *SANS.read().expect("family registry");
530    match requested {
531        Some(name) => loaded_family(name).or_else(|| fallback_for("default", name)),
532        None => {
533            let generic = LOADED
534                .read()
535                .expect("family registry")
536                .as_ref()
537                .is_none_or(|loaded| loaded.generic_sans);
538            if generic {
539                None
540            } else {
541                LOADED
542                    .read()
543                    .expect("family registry")
544                    .as_ref()
545                    .and_then(Loaded::fallback)
546                    .map(interned)
547            }
548        }
549    }
550}
551
552/// The default sans-serif as a cosmic-text family.
553fn sans_family() -> cosmic_text::Family<'static> {
554    match default_family() {
555        Some(name) => cosmic_text::Family::Name(name),
556        None => cosmic_text::Family::SansSerif,
557    }
558}
559
560/// `true` when `text` holds at least one character of the **Arabic** script
561/// (the Arabic, Supplement, Extended-A and Presentation Forms A/B blocks).
562fn contains_arabic(text: &str) -> bool {
563    text.chars().any(|c| {
564        matches!(c as u32,
565            0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF)
566    })
567}
568
569/// The **font family** to use for `text`: the bundled Arabic face when the text
570/// contains Arabic, otherwise the default sans-serif.
571///
572/// This is essential because cosmic-text does **not** fall back across families on
573/// Android, where the platform fallback lists are empty: without an explicit
574/// assignment an Arabic run would render nothing. So the family is chosen by script
575/// at the source, and measurement **and** rendering share the rule.
576pub fn family_for(text: &str) -> cosmic_text::Family<'static> {
577    if contains_arabic(text) {
578        // No Arabic face loaded: the sans is a better guess than a family name that
579        // resolves to nothing, and on the desktop the system usually has one.
580        let arabic = *ARABIC.read().expect("family registry");
581        match arabic.and_then(loaded_family) {
582            Some(name) => cosmic_text::Family::Name(name),
583            None => sans_family(),
584        }
585    } else {
586        sans_family()
587    }
588}
589
590/// The family to draw `text` in when a style **named one**.
591///
592/// # Why a named family does not simply win
593///
594/// A run containing Arabic keeps the registered Arabic face, whatever was named. It is not
595/// a hedge: cosmic-text does not fall back across families on Android, where the platform
596/// fallback lists are empty, so a family without Arabic coverage renders **nothing at
597/// all** — not a substituted glyph, not a box, nothing. Text in an unexpected face is a
598/// smaller failure than a blank screen, and a caller who wants an Arabic family names it
599/// and gets it.
600///
601/// The same reasoning covers a named family that is not loaded: it is matched to the
602/// loaded family it plainly means, or drawn in the default family, and the console says
603/// which — never a name that resolves to nothing.
604///
605/// Coverage is what would settle this properly — asking the face whether it has the
606/// characters — and fontdb does not offer it cheaply. That is a limit, and it is written
607/// down here rather than left for someone to discover on a device.
608pub fn family_for_style(
609    text: &str,
610    family: Option<frus_core::FontFamily>,
611) -> cosmic_text::Family<'static> {
612    use frus_core::FontFamily;
613    match family {
614        // Nothing named: the existing rule, which already chooses by script.
615        None => family_for(text),
616        // Named, but the run needs the Arabic face to be drawn at all.
617        Some(_) if contains_arabic(text) => family_for(text),
618        Some(FontFamily::SansSerif) => sans_family(),
619        Some(FontFamily::Serif) => cosmic_text::Family::Serif,
620        Some(FontFamily::Monospace) => monospace_family(),
621        Some(FontFamily::Named(name)) => match loaded_family(name) {
622            Some(found) => cosmic_text::Family::Name(found),
623            None => {
624                fallback_for("named", name);
625                sans_family()
626            }
627        },
628    }
629}
630
631/// The monospaced family, for the widgets that ask for one. When neither the family
632/// named nor the platform's generic monospace is there — Android without
633/// `bundled-mono` — it is the default family: text in the wrong face, not none.
634pub fn monospace_family() -> cosmic_text::Family<'static> {
635    let requested = *MONO.read().expect("family registry");
636    match requested {
637        Some(name) => match loaded_family(name) {
638            Some(found) => cosmic_text::Family::Name(found),
639            None => {
640                fallback_for("monospace", name);
641                sans_family()
642            }
643        },
644        None => {
645            let generic = LOADED
646                .read()
647                .expect("family registry")
648                .as_ref()
649                .is_none_or(|loaded| loaded.generic_mono);
650            if generic {
651                cosmic_text::Family::Monospace
652            } else {
653                sans_family()
654            }
655        }
656    }
657}
658
659/// The style **actually available** for the default family. Italic when an oblique
660/// face is loaded, upright when none is — because cosmic-text demands an exact style
661/// match, and asking for one that does not exist sends it to platform fallback lists
662/// that are empty on Android. Turning off `bundled-italic` should cost you slanted
663/// text, not text.
664pub fn available_style(italic: bool) -> Style {
665    if italic && ITALIC.load(Ordering::Relaxed) {
666        Style::Italic
667    } else {
668        Style::Normal
669    }
670}
671
672/// Where Android keeps its fonts.
673#[cfg(target_os = "android")]
674const ANDROID_FONT_DIR: &str = "/system/fonts";
675
676/// Loads the font files of `dir` whose lower-cased name `keep` accepts. Returns how many
677/// files were taken; a directory that is not there is a platform without one, and none.
678#[cfg(any(target_os = "android", test))]
679fn load_platform_faces(
680    db: &mut cosmic_text::fontdb::Database,
681    dir: &std::path::Path,
682    keep: impl Fn(&str) -> bool,
683) -> usize {
684    let Ok(entries) = std::fs::read_dir(dir) else {
685        return 0;
686    };
687    let mut taken = 0;
688    for path in entries.flatten().map(|entry| entry.path()) {
689        let name = path
690            .file_name()
691            .and_then(|name| name.to_str())
692            .map(str::to_ascii_lowercase)
693            .unwrap_or_default();
694        let font = [".ttf", ".otf", ".ttc"]
695            .iter()
696            .any(|extension| name.ends_with(extension));
697        if font && keep(&name) && db.load_font_file(&path).is_ok() {
698            taken += 1;
699        }
700    }
701    taken
702}
703
704/// Loads the **emoji** faces from a font directory — every font file whose name says
705/// `emoji` — and nothing else from it. Returns how many files were taken.
706///
707/// Only the emoji faces, because that is the gap: the bundled faces answer for text, and
708/// a platform's whole font directory is hundreds of files. They are taken from the
709/// platform rather than bundled because colour emoji are the platform's own look and the
710/// largest font on it. They then need no fallback list to be found: cosmic-text's last
711/// pass tries every face whose name says `Emoji`, whatever the style asked for.
712#[cfg(any(target_os = "android", test))]
713fn load_emoji_faces(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
714    load_platform_faces(db, dir, |name| name.contains("emoji"))
715}
716
717/// Loads the platform's own **sans** — Roboto's files, not its condensed cut — for when
718/// nothing frus or the application loaded can draw text. Returns how many files were
719/// taken.
720///
721/// It is the last resort, not the default: a build that dropped `bundled-sans` and
722/// registered no face of its own used to draw no text at all on Android, and the platform
723/// has a perfectly good face on disk.
724#[cfg(any(target_os = "android", test))]
725fn load_platform_sans(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
726    load_platform_faces(db, dir, |name| name.starts_with("roboto-"))
727}
728
729/// Builds a ready-to-use `FontSystem`: the system fonts, which provide the emoji
730/// and script fallbacks, **plus** the bundled font, set as the default family. Use
731/// it everywhere a `FontSystem` is created — measurement here, rendering in
732/// `frus-gpu` — for consistent text rendering that does not depend on system fonts,
733/// which may have no resolvable default at all, as on Android.
734///
735/// On Android "the system fonts" used to be **none**: fontdb reads no directory there,
736/// and cosmic-text has no fallback list for the platform, so an emoji in a run was drawn
737/// as an empty box (milestone 506). The platform's emoji faces are loaded explicitly —
738/// and its sans too, when nothing else loaded can draw text (milestone 626).
739pub fn new_font_system() -> FontSystem {
740    let started = web_time::Instant::now();
741    let font_system = build_font_system();
742    if let Ok(mut loading) = FONT_LOADING.lock() {
743        loading.0 += started.elapsed();
744        loading.1 += 1;
745    }
746    font_system
747}
748
749/// How long building the font systems took, all together, and how many were built — one for
750/// measuring text, one for drawing it: a part of an application's time to its first frame
751/// (milestone 683, #211). The system's fonts are read for each.
752pub fn font_loading() -> (std::time::Duration, u32) {
753    FONT_LOADING
754        .lock()
755        .map(|loading| *loading)
756        .unwrap_or_default()
757}
758
759static FONT_LOADING: Mutex<(std::time::Duration, u32)> = Mutex::new((std::time::Duration::ZERO, 0));
760
761fn build_font_system() -> FontSystem {
762    let mut font_system = FontSystem::new();
763    let db = font_system.db_mut();
764    #[cfg(target_os = "android")]
765    load_emoji_faces(db, std::path::Path::new(ANDROID_FONT_DIR));
766    #[cfg(feature = "bundled-sans")]
767    {
768        db.load_font_data(DEJAVU_SANS.to_vec());
769        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
770    }
771    #[cfg(feature = "bundled-italic")]
772    {
773        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
774        db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
775    }
776    #[cfg(feature = "bundled-mono")]
777    db.load_font_data(DEJAVU_MONO.to_vec());
778    #[cfg(feature = "bundled-arabic")]
779    {
780        db.load_font_data(NOTO_ARABIC.to_vec());
781        db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
782    }
783    // Whatever the application supplied itself, over the bundled faces.
784    for face in EXTRA_FONTS.lock().expect("font registry").iter() {
785        db.load_font_data(face.clone());
786    }
787    // Nothing loaded draws default text: the platform's own sans, rather than a blank
788    // screen.
789    #[cfg(target_os = "android")]
790    {
791        let requested = *SANS.read().expect("family registry");
792        if Loaded::of(db).wants_platform_sans(requested)
793            && load_platform_sans(db, std::path::Path::new(ANDROID_FONT_DIR)) > 0
794        {
795            log::info!(
796                "frus: no bundled or registered face draws text; using the platform's Roboto"
797            );
798        }
799    }
800    take_stock(db);
801    font_system
802}
803
804static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
805
806fn font_system() -> &'static Mutex<FontSystem> {
807    FONT_SYSTEM.get_or_init(|| Mutex::new(new_font_system()))
808}
809
810/// Everything about a measurement that can change its answer. The weight and the
811/// style are the **resolved** ones — what the database can actually serve — so a
812/// Medium asked for on a family that only has Regular hits the same entry as the
813/// Regular, which is the same shaping either way. Floats are keyed by their bits:
814/// two sizes that are bit-identical measure identically, and no other pair needs to
815/// share an entry.
816#[derive(PartialEq, Eq, Hash)]
817struct MeasureKey {
818    text: String,
819    size: u32,
820    weight: u16,
821    italic: bool,
822    max_width: Option<u32>,
823    /// The line height these words were measured at, in bits. A style may name one, so it
824    /// is part of the question and not a constant.
825    line_h: u32,
826    /// The family they were measured in. Different faces have different widths, which is
827    /// the reason for naming one at all.
828    family: Option<frus_core::FontFamily>,
829    /// The letter spacing, in bits: two spacings give two widths.
830    letter_spacing: u32,
831}
832
833/// How many entries a generation holds before it is retired. Two generations live at
834/// once, so this bounds the cache at roughly `2 × CAP` measurements — a few hundred
835/// kilobytes, against the ~290 µs a twelve-row screen was spending per frame
836/// re-measuring strings that had not changed (milestone 299).
837const CACHE_CAP: usize = 2048;
838
839/// A two-generation cache. A string still being drawn is found in `current` or
840/// promoted out of `previous`, so it survives a rotation; a string that has gone —
841/// last second's clock, yesterday's search box — falls out with the generation it
842/// was in. That is the whole eviction policy, and it needs no timestamps.
843#[derive(Default)]
844struct MeasureCache {
845    current: std::collections::HashMap<MeasureKey, Size>,
846    previous: std::collections::HashMap<MeasureKey, Size>,
847}
848
849static MEASURE_CACHE: Mutex<Option<MeasureCache>> = Mutex::new(None);
850
851/// Forgets every measurement. Called whenever what a face measures to can have
852/// changed — a font registered, a family renamed — because an answer from before
853/// that is simply wrong, not merely stale.
854fn forget_measurements() {
855    if let Ok(mut cache) = MEASURE_CACHE.lock() {
856        *cache = None;
857    }
858}
859
860/// The weight **actually available** in the default family closest to the one
861/// requested. This is essential: cosmic-text demands an **exact** weight match on the
862/// primary family, and a missing weight (Medium 500 on DejaVu) sends it off to the
863/// platform fallback lists — which do not exist on Android ("no default font found", a
864/// panic caught on the device). Routing every `Attrs` through here is what makes
865/// rendering deterministic.
866///
867/// "Available" is read from the faces loaded, not assumed: the bundled sans has 400 and
868/// 700, so Medium draws as Regular and SemiBold as Bold; an application that registers
869/// Medium and SemiBold faces of its own gets them, and a variable face draws every weight
870/// its axis spans (milestone 626). With the generic family in charge — nothing named, on
871/// a desktop — the answer is the bundled sans's, 400 or 700.
872pub fn available_weight(weight: FontWeight) -> u16 {
873    let wanted = weight.to_u16();
874    let have = WEIGHTS.read().expect("family registry");
875    if have.is_empty() {
876        return if wanted < 550 { 400 } else { 700 };
877    }
878    nearest_weight(wanted, &have)
879}
880
881/// What a baseline depends on: the size and the **resolved** weight and style. The
882/// text does not enter into it — a baseline is a property of the font at a size, not of
883/// what is written in it.
884#[derive(Clone, Copy, PartialEq, Eq, Hash)]
885struct BaselineKey {
886    size: u32,
887    weight: u16,
888    italic: bool,
889}
890
891static BASELINES: std::sync::LazyLock<
892    std::sync::Mutex<std::collections::HashMap<BaselineKey, f32>>,
893> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
894
895/// `attrs` with **letter spacing**: `letter_spacing` logical pixels after every character,
896/// which the shaper takes as a fraction of the size (milestone 623). Every place that shapes
897/// text goes through this, so a measure and a paint space the same words alike.
898pub fn spaced(attrs: Attrs<'static>, letter_spacing: f32, size_px: f32) -> Attrs<'static> {
899    if letter_spacing == 0.0 || size_px <= 0.0 {
900        attrs
901    } else {
902        attrs.letter_spacing(letter_spacing / size_px)
903    }
904}
905
906/// The line height for a given font size, in pixels, **for a style that says nothing
907/// about it**.
908///
909/// A style that *does* say something answers for itself:
910/// [`ResolvedTextStyle::line_height`]. Prefer that wherever a style is in reach — this
911/// form cannot honour a `height` it was never shown, and a caller holding a style and
912/// calling this anyway is the same measure-and-paint disagreement in miniature.
913pub fn line_height(size_px: f32) -> f32 {
914    size_px * LINE_HEIGHT_FACTOR
915}
916
917/// The **alphabetic baseline** of a line of text at `size_px`: the distance from the
918/// top of the line box down to the line the letters sit on.
919///
920/// It is the number two pieces of text need in order to agree on where "the same line"
921/// is. Sizes and line heights differ, so aligning two runs by their tops or their
922/// bottoms puts them at different heights; aligning them by this puts them where a
923/// reader expects.
924///
925/// It is **shaped**, not derived from the size. The ascent belongs to the font the
926/// fallback chain actually chose, and guessing it from the point size is wrong by a few
927/// per cent per family — enough to see when two labels sit side by side, which is the
928/// only situation this number is ever used in.
929pub fn baseline(size_px: f32, weight: FontWeight, italic: bool) -> f32 {
930    // The system is built before the key is resolved, for the reason `measure_wrapped`
931    // gives: resolving reads state that building it sets.
932    let _ = font_system();
933    let key = BaselineKey {
934        size: size_px.to_bits(),
935        weight: available_weight(weight),
936        italic: available_style(italic) == Style::Italic,
937    };
938    if let Some(cached) = BASELINES.lock().expect("baseline cache").get(&key) {
939        return *cached;
940    }
941
942    let line_h = line_height(size_px);
943    let mut font_system = font_system().lock().expect("FontSystem lock");
944    let metrics = Metrics::new(size_px, line_h);
945    let mut buffer = Buffer::new(&mut font_system, metrics);
946    // Two letters with an ascender and a descender, so the line is shaped at its full
947    // height rather than at the height of whatever happens to be in it.
948    let probe = "Hg";
949    let attrs = Attrs::new()
950        .family(family_for(probe))
951        .weight(Weight(available_weight(weight)))
952        .style(available_style(italic));
953    buffer.set_text(probe, &attrs, Shaping::Advanced, None);
954    buffer.shape_until_scroll(&mut font_system, false);
955    // `line_y` is where the renderer puts the baseline, so taking it from the same
956    // place is what keeps layout and paint talking about the same line.
957    let baseline = buffer
958        .layout_runs()
959        .next()
960        .map(|run| run.line_y)
961        .unwrap_or(size_px);
962    drop(font_system);
963    BASELINES
964        .lock()
965        .expect("baseline cache")
966        .insert(key, baseline);
967    baseline
968}
969
970/// The first baseline of a sequence of styled runs: the **largest** of their
971/// baselines, since they share a line and the tallest ascender sets where it sits.
972pub fn baseline_of_runs(runs: &[TextRun]) -> Option<f32> {
973    runs.iter()
974        .map(|run| baseline(run.size, run.weight, run.italic))
975        .fold(None, |acc: Option<f32>, b| {
976            Some(acc.map_or(b, |a| a.max(b)))
977        })
978}
979
980/// Measures a text's natural size (multiple lines allowed), in pixels, at regular
981/// weight. See [`measure_styled`] for weight and italics.
982pub fn measure(text: &str, size_px: f32) -> Size {
983    measure_styled(text, size_px, FontWeight::Regular, false)
984}
985
986/// Measures `text` under a [`TextStyle`], **resolving whatever it left open** to the
987/// framework's own defaults.
988///
989/// Every widget that measures a label wants this and used to spell it out as three
990/// arguments. Three arguments is three chances to pass a size from one style and a weight
991/// from another, which draws text the layout never measured.
992pub fn measure_style(text: &str, style: TextStyle) -> Size {
993    measure_resolved(text, &style.resolved())
994}
995
996/// Measures `text` under a style that has **already** been resolved — the same thing one
997/// step further down, for the code that has done the resolving once and is measuring
998/// several times against it.
999pub fn measure_resolved(text: &str, style: &ResolvedTextStyle) -> Size {
1000    measure_wrapped_resolved(text, style, None)
1001}
1002
1003/// The height a box needs to hold **one line** of `style` with `padding` of room around
1004/// it: `min`, unless the reader asked for type that does not fit in `min`.
1005///
1006/// It is the reference's rule for its own components — a default height is a *floor*, and
1007/// content taller than it wins — written once rather than as a `max` remembered at each of
1008/// the places that need it. A component whose height is a bare constant clips its own text
1009/// the moment somebody turns the system font size up, and says nothing about it.
1010pub fn line_box(min: f32, style: &ResolvedTextStyle, padding: f32) -> f32 {
1011    // Rounded **up**. The layout works in whole pixels, and a box that came out at 43 for
1012    // a line needing 43.2 clips it — by a fifth of a pixel, which is still a clip.
1013    min.max(fits(style.line_height() + padding))
1014}
1015
1016/// Measures `text` under an already-resolved style, **wrapping** at `max_width`. The
1017/// resolved counterpart of [`measure_wrapped`], for a paragraph whose style has been
1018/// settled once and must be measured and painted at the same size.
1019pub fn measure_wrapped_resolved(
1020    text: &str,
1021    style: &ResolvedTextStyle,
1022    max_width: Option<f32>,
1023) -> Size {
1024    // Through `measure_at`, not `measure_wrapped`: the style may name a line height, and
1025    // going by the size alone would measure at one height what the renderer draws at
1026    // another.
1027    measure_at(text, style, max_width)
1028}
1029
1030/// Measures a **styled** text's natural size; weight and italics count, since bold
1031/// is wider than regular and the layout has to know.
1032pub fn measure_styled(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Size {
1033    measure_wrapped(text, size_px, weight, italic, None)
1034}
1035
1036/// Measures a styled text **under a width constraint**: beyond `max_width` the text
1037/// wraps and the height grows. `None` means unconstrained, giving the natural size.
1038/// This is the measurement wired into taffy's measure closure for paragraphs.
1039pub fn measure_wrapped(
1040    text: &str,
1041    size_px: f32,
1042    weight: FontWeight,
1043    italic: bool,
1044    max_width: Option<f32>,
1045) -> Size {
1046    let style = ResolvedTextStyle {
1047        weight,
1048        italic,
1049        ..ResolvedTextStyle::exact(size_px)
1050    };
1051    measure_at(text, &style, max_width)
1052}
1053
1054/// The measurement itself, under a **whole resolved style**.
1055///
1056/// Every public form funnels here, and it takes the style rather than its parts because
1057/// a style may name a line height, a family and a letter spacing (milestone 623): two
1058/// callers each passing some of them is how a measure and a paint come to disagree about
1059/// where the second line starts, or how wide the first one is.
1060fn measure_at(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Size {
1061    let (size_px, weight, italic) = (style.size, style.weight, style.italic);
1062    let (line_h, family, letter_spacing) =
1063        (style.line_height(), style.family, style.letter_spacing);
1064    if text.is_empty() {
1065        // Whole, like every other measurement here: a line height is a fraction of a
1066        // size — 19.2 for a 16 px label — and an empty label reserving 19.2 is handed a
1067        // box of 19, which clips the caret and any text put there later.
1068        return Size::new(0.0, fits(line_h));
1069    }
1070
1071    // The key records the **resolved** weight and style, and resolving reads state
1072    // that building the font system sets (`ITALIC`, from the faces actually loaded).
1073    // So the system is built first: otherwise the very first measurement would be
1074    // filed under what was true before it existed.
1075    let _ = font_system();
1076
1077    // Shaping the same string again every frame was three quarters of what building a
1078    // frame cost (milestone 299). A hit here also skips the `FontSystem` lock, which
1079    // the renderer wants at the same time.
1080    let key = MeasureKey {
1081        text: text.to_string(),
1082        size: size_px.to_bits(),
1083        weight: available_weight(weight),
1084        italic: available_style(italic) == Style::Italic,
1085        max_width: max_width.map(f32::to_bits),
1086        // Two line heights give two different answers for the same words, so they cannot
1087        // share a cache entry. Nor can two families: that is the point of naming one.
1088        line_h: line_h.to_bits(),
1089        family,
1090        letter_spacing: letter_spacing.to_bits(),
1091    };
1092    if let Some(size) = cached_measurement(&key) {
1093        return size;
1094    }
1095
1096    let mut font_system = font_system().lock().expect("FontSystem lock");
1097    let metrics = Metrics::new(size_px, line_h);
1098    let mut buffer = Buffer::new(&mut font_system, metrics);
1099    // A constrained width (wrapping) or a free one; the height is always free.
1100    buffer.set_size(max_width, None);
1101    let attrs = spaced(
1102        Attrs::new()
1103            // The face the **renderer** will use, not the default: measuring in one family
1104            // and drawing in another reserves a width for letters of a different shape.
1105            .family(family_for_style(text, family))
1106            .weight(Weight(available_weight(weight)))
1107            .style(available_style(italic)),
1108        letter_spacing,
1109        size_px,
1110    );
1111    buffer.set_text(text, &attrs, Shaping::Advanced, None);
1112    buffer.shape_until_scroll(&mut font_system, false);
1113
1114    let mut width = 0.0_f32;
1115    let mut lines = 0.0_f32;
1116    for run in buffer.layout_runs() {
1117        width = width.max(run.line_w);
1118        lines += 1.0;
1119    }
1120
1121    // **Rounded up**, and this matters more than it looks. The layout engine rounds
1122    // the boxes it hands out to whole pixels, so a natural width of 146.4 becomes a
1123    // box of 146 — narrower than the text that asked for it. The text is then shaped
1124    // again at 146 when painting, wraps onto a second line, and overlaps whatever the
1125    // layout put below it on the strength of a one-line height. A ceiling here is what
1126    // keeps the measurement and the painting talking about the same box.
1127    //
1128    // Under a constraint the ceiling is clamped back to it: the text did fit that
1129    // width, and a box a fraction wider than allowed is a different bug.
1130    let width = match max_width {
1131        Some(max) => fits(width).min(max),
1132        None => fits(width),
1133    };
1134    // **And the height too**, which milestone 289 did not do: it fixed the width the
1135    // wrapping bug presented on and left the other axis fractional. A line height is
1136    // typically not whole — 14.4 for a 12 px line — so a two-line paragraph measured
1137    // itself at 28.8 and, at a top edge that rounded up, was handed 28. The same bug, the
1138    // same function, the axis nobody looked at (issue #54).
1139    let measured = Size::new(width, fits(lines.max(1.0) * line_h));
1140    remember_measurement(key, measured);
1141    measured
1142}
1143
1144/// The cached answer for `key`, promoting it out of the retiring generation if that
1145/// is where it was found.
1146fn cached_measurement(key: &MeasureKey) -> Option<Size> {
1147    let mut guard = MEASURE_CACHE.lock().ok()?;
1148    let cache = guard.as_mut()?;
1149    if let Some(size) = cache.current.get(key) {
1150        return Some(*size);
1151    }
1152    let size = *cache.previous.get(key)?;
1153    // Still in use, so it moves forward rather than falling out with its generation.
1154    cache.current.insert(
1155        MeasureKey {
1156            text: key.text.clone(),
1157            ..*key
1158        },
1159        size,
1160    );
1161    Some(size)
1162}
1163
1164fn remember_measurement(key: MeasureKey, size: Size) {
1165    let Ok(mut guard) = MEASURE_CACHE.lock() else {
1166        return;
1167    };
1168    let cache = guard.get_or_insert_with(MeasureCache::default);
1169    if cache.current.len() >= CACHE_CAP {
1170        cache.previous = std::mem::take(&mut cache.current);
1171    }
1172    cache.current.insert(key, size);
1173}
1174
1175/// The **visual lines** a piece of text breaks into inside a box `max_width` wide, as
1176/// byte ranges into `text`.
1177///
1178/// The reference's `maxLines` and `overflow` both need this and neither can be answered by
1179/// a measurement: a height tells you how many lines there are, not *where they broke*, and
1180/// a cut has to fall on a break the shaper chose or the words move.
1181///
1182/// Ranges rather than strings, because the caller wants a **prefix** of the original: a
1183/// text handed to the renderer as separate lines is a paragraph per line, and rules that
1184/// span a paragraph — a justified block leaving its last line ragged — stop working.
1185///
1186/// Not cached. Only text that asked for a line limit gets here, and the shaping it does is
1187/// the same shaping the renderer does again; everything else goes through the cached
1188/// measurement.
1189pub fn line_spans(
1190    text: &str,
1191    size_px: f32,
1192    weight: FontWeight,
1193    italic: bool,
1194    max_width: Option<f32>,
1195    soft_wrap: bool,
1196) -> Vec<std::ops::Range<usize>> {
1197    let style = ResolvedTextStyle {
1198        weight,
1199        italic,
1200        ..ResolvedTextStyle::exact(size_px)
1201    };
1202    line_spans_resolved(text, &style, max_width, soft_wrap)
1203}
1204
1205/// [`line_spans`] under a whole resolved style: its line height, its family and its letter
1206/// spacing break the lines as the renderer will (milestone 623).
1207pub fn line_spans_resolved(
1208    text: &str,
1209    style: &ResolvedTextStyle,
1210    max_width: Option<f32>,
1211    soft_wrap: bool,
1212) -> Vec<std::ops::Range<usize>> {
1213    let size_px = style.size;
1214    let mut font_system = font_system().lock().expect("FontSystem lock");
1215    let metrics = Metrics::new(size_px, style.line_height());
1216    let mut buffer = Buffer::new(&mut font_system, metrics);
1217    if !soft_wrap {
1218        buffer.set_wrap(cosmic_text::Wrap::None);
1219    }
1220    buffer.set_size(max_width, None);
1221    let attrs = spaced(
1222        Attrs::new()
1223            .family(family_for_style(text, style.family))
1224            .weight(Weight(available_weight(style.weight)))
1225            .style(available_style(style.italic)),
1226        style.letter_spacing,
1227        size_px,
1228    );
1229    buffer.set_text(text, &attrs, Shaping::Advanced, None);
1230    buffer.shape_until_scroll(&mut font_system, false);
1231
1232    // A buffer line per explicit newline; a layout run's glyph offsets are into its own
1233    // buffer line, so the starts of those lines are what turns them into offsets into the
1234    // whole.
1235    let mut line_start = Vec::new();
1236    let mut at = 0usize;
1237    for line in &buffer.lines {
1238        line_start.push(at);
1239        at += line.text().len() + 1;
1240    }
1241
1242    let mut spans = Vec::new();
1243    for run in buffer.layout_runs() {
1244        let base = line_start.get(run.line_i).copied().unwrap_or(0);
1245        // The glyphs are in **visual** order, so a right-to-left line has its last byte
1246        // first: the span is the extent of the run, not its ends in order.
1247        let start = run.glyphs.iter().map(|g| g.start).min();
1248        let end = run.glyphs.iter().map(|g| g.end).max();
1249        match (start, end) {
1250            (Some(start), Some(end)) => spans.push(base + start..base + end),
1251            // A blank line between two paragraphs has no glyphs and is still a line.
1252            _ => spans.push(base..base),
1253        }
1254    }
1255    // An empty paragraph still occupies a line, and a caller counting them would
1256    // otherwise see none.
1257    if spans.is_empty() {
1258        spans.push(0..0);
1259    }
1260    spans
1261}
1262
1263/// Measures a **rich text**'s natural size — resolved runs with mixed styles and
1264/// sizes: the longest line's width, and the shaped lines' real height.
1265pub fn measure_runs(runs: &[TextRun]) -> Size {
1266    measure_runs_wrapped(runs, None)
1267}
1268
1269/// Measures a rich text **under a width constraint**: beyond `max_width` the runs
1270/// wrap. `None` means unconstrained.
1271pub fn measure_runs_wrapped(runs: &[TextRun], max_width: Option<f32>) -> Size {
1272    if runs.iter().all(|r| r.text.is_empty()) {
1273        return Size::new(0.0, 0.0);
1274    }
1275    let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
1276
1277    let mut font_system = font_system().lock().expect("FontSystem lock");
1278    let metrics = Metrics::new(base, line_height(base));
1279    let mut buffer = Buffer::new(&mut font_system, metrics);
1280    buffer.set_size(max_width, None);
1281    let spans = runs.iter().map(|run| {
1282        (
1283            run.text.as_str(),
1284            spaced(
1285                Attrs::new()
1286                    .family(family_for(&run.text))
1287                    .weight(Weight(available_weight(run.weight)))
1288                    .style(available_style(run.italic))
1289                    .metrics(Metrics::new(run.size, line_height(run.size))),
1290                run.letter_spacing,
1291                run.size,
1292            ),
1293        )
1294    });
1295    buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
1296    buffer.shape_until_scroll(&mut font_system, false);
1297
1298    let mut width = 0.0_f32;
1299    let mut height = 0.0_f32;
1300    for run in buffer.layout_runs() {
1301        width = width.max(run.line_w);
1302        height = height.max(run.line_top + run.line_height);
1303    }
1304    // Rounded up for the same reason as [`measure_wrapped`]: a box rounded down below
1305    // the width the text asked for makes the text wrap when it is painted, on a height
1306    // that says it did not.
1307    let width = match max_width {
1308        Some(max) => fits(width).min(max),
1309        None => fits(width),
1310    };
1311    // The height as well, for the reason above: a run's line height is a fraction of its
1312    // size and lands whole only by accident.
1313    Size::new(width, fits(height))
1314}
1315
1316/// The byte offset at which a rich text runs past `max_lines` visual lines, and how many
1317/// lines it actually took — `None` when it fits.
1318///
1319/// The offset is into the **concatenation** of the runs' texts, which is what the shaper
1320/// was given and the only coordinate the runs and the lines share. Splitting the runs
1321/// there is the caller's job, and cheap once the number is known.
1322///
1323/// Rich text is cut here rather than in the widget because the cut has to land on a break
1324/// the shaper chose, and only the shaper knows where those are — the same reason
1325/// [`line_spans`] exists, one primitive along.
1326pub fn runs_cut_at(
1327    runs: &[TextRun],
1328    max_width: Option<f32>,
1329    soft_wrap: bool,
1330    max_lines: usize,
1331) -> Option<usize> {
1332    if runs.iter().all(|r| r.text.is_empty()) {
1333        return None;
1334    }
1335    let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
1336    let mut font_system = font_system().lock().expect("FontSystem lock");
1337    let metrics = Metrics::new(base, line_height(base));
1338    let mut buffer = Buffer::new(&mut font_system, metrics);
1339    if !soft_wrap {
1340        buffer.set_wrap(cosmic_text::Wrap::None);
1341    }
1342    buffer.set_size(max_width, None);
1343    let spans = runs.iter().map(|run| {
1344        (
1345            run.text.as_str(),
1346            spaced(
1347                Attrs::new()
1348                    .family(family_for(&run.text))
1349                    .weight(Weight(available_weight(run.weight)))
1350                    .style(available_style(run.italic))
1351                    .metrics(Metrics::new(run.size, line_height(run.size))),
1352                run.letter_spacing,
1353                run.size,
1354            ),
1355        )
1356    });
1357    buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
1358    buffer.shape_until_scroll(&mut font_system, false);
1359
1360    // A buffer line per explicit newline; the offsets a layout run carries are into its
1361    // own buffer line, so the starts of those lines are what turns them back into offsets
1362    // into the whole.
1363    let mut line_start = Vec::new();
1364    let mut at = 0usize;
1365    for line in &buffer.lines {
1366        line_start.push(at);
1367        at += line.text().len() + 1;
1368    }
1369    for (index, run) in buffer.layout_runs().enumerate() {
1370        if index < max_lines {
1371            continue;
1372        }
1373        let start = run.glyphs.iter().map(|g| g.start).min().unwrap_or(0);
1374        return Some(line_start.get(run.line_i).copied().unwrap_or(0) + start);
1375    }
1376    None
1377}
1378
1379/// One shaped line of a [`TextLayout`]: the `x` offsets of every **character
1380/// boundary**, taken from the real glyphs, kerning and ligatures included.
1381struct LayoutLine {
1382    /// The line's first boundary, as a character index global to the text.
1383    start_char: usize,
1384    /// The `x` of every character boundary on the line (`chars + 1` entries).
1385    offsets: Vec<f32>,
1386    /// The line's top edge.
1387    top: f32,
1388    /// The line's height.
1389    height: f32,
1390}
1391
1392/// A text's **shaped** layout — a single cosmic-text pass — exposing the geometry an
1393/// editing widget needs: caret position by character index, reverse hit-testing, and
1394/// selection rectangles. Coordinates are **local** to the text, with the origin at
1395/// its top-left corner. Indices are in **characters** — frus's editing convention —
1396/// with boundaries `0..=len`.
1397///
1398/// Unlike a prefix measurement re-shaped substring by substring, the offsets come
1399/// from the **whole** shaped line: consistent with one another (kerning), and
1400/// computed in one pass instead of `n`.
1401pub struct TextLayout {
1402    lines: Vec<LayoutLine>,
1403    size: Size,
1404    /// The total character count — the last valid boundary.
1405    chars: usize,
1406}
1407
1408impl TextLayout {
1409    /// Shapes `text` (multiple lines allowed, width unconstrained) in the given style
1410    /// and extracts its geometry.
1411    pub fn new(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Self {
1412        Self::wrapped(text, size_px, weight, italic, None)
1413    }
1414
1415    /// Like [`TextLayout::new`], but **wraps** the text at `max_width` — a soft wrap,
1416    /// as in a multi-line field. `None` is unconstrained, where only `\n` breaks.
1417    ///
1418    /// Every **visual line** (one cosmic-text `LayoutRun`) is delimited by **its
1419    /// glyphs' bytes**, not by `run.text` — which is the whole *hard* line, repeated
1420    /// for each wrap. A soft wrap therefore fabricates no phantom character, and each
1421    /// line's `start_char` comes from its hard line's byte offset — exact indexing
1422    /// straight through the wraps.
1423    pub fn wrapped(
1424        text: &str,
1425        size_px: f32,
1426        weight: FontWeight,
1427        italic: bool,
1428        max_width: Option<f32>,
1429    ) -> Self {
1430        Self::shaped(
1431            text,
1432            size_px,
1433            weight,
1434            italic,
1435            max_width,
1436            line_height(size_px),
1437            None,
1438            0.0,
1439        )
1440    }
1441
1442    /// Like [`TextLayout::wrapped`], under a style that has **already been resolved**: its
1443    /// line height and its face, which `wrapped` knows nothing of.
1444    ///
1445    /// For text that is drawn from a [`ResolvedTextStyle`] and must be *hit* where it is
1446    /// drawn — a selectable paragraph. A layout at the default leading over a paragraph
1447    /// painted at another puts every line after the first somewhere else, and a tap lands
1448    /// on the wrong word.
1449    pub fn resolved(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Self {
1450        Self::shaped(
1451            text,
1452            style.size,
1453            style.weight,
1454            style.italic,
1455            max_width,
1456            style.line_height(),
1457            style.family,
1458            style.letter_spacing,
1459        )
1460    }
1461
1462    // A text's whole shaping, argument by argument; grouping them would only move them.
1463    #[allow(clippy::too_many_arguments)]
1464    fn shaped(
1465        text: &str,
1466        size_px: f32,
1467        weight: FontWeight,
1468        italic: bool,
1469        max_width: Option<f32>,
1470        fallback_h: f32,
1471        family: Option<frus_core::FontFamily>,
1472        letter_spacing: f32,
1473    ) -> Self {
1474        let mut lines: Vec<LayoutLine> = Vec::new();
1475        let mut width = 0.0_f32;
1476        let mut height = 0.0_f32;
1477
1478        if !text.is_empty() {
1479            // The byte offset of every **hard** line's start (those split by `\n`).
1480            let hard: Vec<&str> = text.split('\n').collect();
1481            let mut line_byte_start = Vec::with_capacity(hard.len());
1482            {
1483                let mut b = 0usize;
1484                for l in &hard {
1485                    line_byte_start.push(b);
1486                    b += l.len() + 1; // +1 for the `\n`
1487                }
1488            }
1489
1490            let mut font_system = font_system().lock().expect("FontSystem lock");
1491            let metrics = Metrics::new(size_px, fallback_h);
1492            let mut buffer = Buffer::new(&mut font_system, metrics);
1493            buffer.set_size(max_width, None);
1494            let attrs = spaced(
1495                Attrs::new()
1496                    .family(family_for_style(text, family))
1497                    .weight(Weight(available_weight(weight)))
1498                    .style(available_style(italic)),
1499                letter_spacing,
1500                size_px,
1501            );
1502            buffer.set_text(text, &attrs, Shaping::Advanced, None);
1503            buffer.shape_until_scroll(&mut font_system, false);
1504
1505            // Collect the runs so we can look at the next one, which ends this segment.
1506            let runs: Vec<_> = buffer.layout_runs().collect();
1507            for (idx, run) in runs.iter().enumerate() {
1508                let line_text = hard[run.line_i];
1509                let first_of_line = idx == 0 || runs[idx - 1].line_i != run.line_i;
1510                // The segment [lo, hi) of the hard line, in bytes, that this visual line
1511                // carries: from its first glyph (0 if it is the first visual line) to the
1512                // first glyph of the next visual line of the same hard line, or the end
1513                // otherwise — which takes in the break space, absent from the glyphs.
1514                let lo = if first_of_line {
1515                    0
1516                } else {
1517                    run.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
1518                };
1519                let hi = runs
1520                    .get(idx + 1)
1521                    .filter(|r| r.line_i == run.line_i)
1522                    .and_then(|r| r.glyphs.iter().map(|g| g.start).min())
1523                    .unwrap_or(line_text.len());
1524
1525                // The segment's character boundaries, in bytes relative to the hard line.
1526                let span = &line_text[lo..hi];
1527                let char_bytes: Vec<usize> = span.char_indices().map(|(b, _)| lo + b).collect();
1528                let n = char_bytes.len();
1529                let mut offsets = vec![f32::NAN; n + 1];
1530                offsets[0] = 0.0;
1531
1532                // Each glyph covers a byte cluster [start, end) over [x, x+w), where x is
1533                // **local to the visual line**; interior boundaries are interpolated.
1534                for glyph in run.glyphs.iter() {
1535                    let covered: Vec<usize> = (0..n)
1536                        .filter(|&i| char_bytes[i] >= glyph.start && char_bytes[i] < glyph.end)
1537                        .collect();
1538                    let k = covered.len().max(1) as f32;
1539                    for (j, &i) in covered.iter().enumerate() {
1540                        offsets[i] = glyph.x + glyph.w * (j as f32 / k);
1541                    }
1542                    if let Some(next) = (0..=n).find(|&i| {
1543                        let b = if i == n {
1544                            lo + span.len()
1545                        } else {
1546                            char_bytes[i]
1547                        };
1548                        b == glyph.end
1549                    }) {
1550                        offsets[next] = glyph.x + glyph.w;
1551                    }
1552                }
1553                // Boundaries left without a glyph (the break space) keep continuity.
1554                for i in 1..=n {
1555                    if offsets[i].is_nan() {
1556                        offsets[i] = offsets[i - 1];
1557                    }
1558                }
1559
1560                let start_char = text[..line_byte_start[run.line_i] + lo].chars().count();
1561                width = width.max(run.line_w);
1562                height = height.max(run.line_top + run.line_height);
1563                lines.push(LayoutLine {
1564                    start_char,
1565                    offsets,
1566                    top: run.line_top,
1567                    height: run.line_height,
1568                });
1569            }
1570        }
1571
1572        // Empty text, or no shaped line: a synthetic empty line keeps caret and hit
1573        // defined, with the caret at x = 0.
1574        if lines.is_empty() {
1575            lines.push(LayoutLine {
1576                start_char: 0,
1577                offsets: vec![0.0],
1578                top: 0.0,
1579                height: fallback_h,
1580            });
1581            height = fallback_h;
1582        }
1583
1584        let chars = text.chars().count();
1585        Self {
1586            lines,
1587            size: Size::new(width, height),
1588            chars,
1589        }
1590    }
1591
1592    /// The shaped text's natural size.
1593    pub fn size(&self) -> Size {
1594        self.size
1595    }
1596
1597    /// The line containing the character boundary `index`.
1598    fn line_of(&self, index: usize) -> &LayoutLine {
1599        self.lines
1600            .iter()
1601            .rev()
1602            .find(|line| index >= line.start_char)
1603            .unwrap_or(&self.lines[0])
1604    }
1605
1606    /// The caret's rectangle at boundary `index`, of zero width — it is up to the
1607    /// widget to choose the stroke thickness. `index` is clamped to the text.
1608    pub fn caret_rect(&self, index: usize) -> Rect {
1609        let index = index.min(self.chars);
1610        let line = self.line_of(index);
1611        let local = (index - line.start_char).min(line.offsets.len() - 1);
1612        Rect::new(line.offsets[local], line.top, 0.0, line.height)
1613    }
1614
1615    /// The character boundary **closest** to `point`, in text-local coordinates. The
1616    /// `y` picks the line (clamped), the `x` picks the boundary.
1617    pub fn hit_test(&self, point: Point) -> usize {
1618        let line = self
1619            .lines
1620            .iter()
1621            .find(|line| point.y < line.top + line.height)
1622            .unwrap_or(self.lines.last().expect("at least one line"));
1623
1624        let mut best = 0;
1625        let mut best_dist = f32::MAX;
1626        for (i, x) in line.offsets.iter().enumerate() {
1627            let dist = (x - point.x).abs();
1628            if dist < best_dist {
1629                best_dist = dist;
1630                best = i;
1631            }
1632        }
1633        (line.start_char + best).min(self.chars)
1634    }
1635
1636    /// The rectangles covering the character range `[start, end)`, one per line
1637    /// crossed; empty ones are omitted.
1638    pub fn selection_rects(&self, start: usize, end: usize) -> Vec<Rect> {
1639        let (start, end) = (start.min(self.chars), end.min(self.chars));
1640        if start >= end {
1641            return Vec::new();
1642        }
1643        let mut rects = Vec::new();
1644        for line in &self.lines {
1645            let line_len = line.offsets.len() - 1;
1646            let lo = start.max(line.start_char);
1647            let hi = end.min(line.start_char + line_len);
1648            if lo >= hi {
1649                continue;
1650            }
1651            let x0 = line.offsets[lo - line.start_char];
1652            let x1 = line.offsets[hi - line.start_char];
1653            if x1 > x0 {
1654                rects.push(Rect::new(x0, line.top, x1 - x0, line.height));
1655            }
1656        }
1657        rects
1658    }
1659}
1660
1661#[cfg(test)]
1662mod tests {
1663
1664    /// **Letter spacing widens a word by its spacing, once per character** (milestone 623):
1665    /// a word of eight letters spaced 2 px is about 16 px wider, and not the same width as
1666    /// the unspaced word cached a moment before — the spacing is part of the question.
1667    /// Negative spacing draws the letters closer.
1668    #[test]
1669    fn letter_spacing_widens_a_word_by_its_spacing() {
1670        let word = "Spacious";
1671        let plain = ResolvedTextStyle::exact(16.0);
1672        let spaced = ResolvedTextStyle {
1673            letter_spacing: 2.0,
1674            ..plain
1675        };
1676        let tight = ResolvedTextStyle {
1677            letter_spacing: -0.5,
1678            ..plain
1679        };
1680        let w0 = measure_resolved(word, &plain).width;
1681        let w2 = measure_resolved(word, &spaced).width;
1682        let wt = measure_resolved(word, &tight).width;
1683        let added = w2 - w0;
1684        assert!(
1685            (added - 16.0).abs() <= 2.5,
1686            "eight letters, two pixels each: {added} added"
1687        );
1688        assert!(wt < w0, "negative spacing tightens: {wt} vs {w0}");
1689        // And the layout that places the caret agrees with the measurement.
1690        let layout = TextLayout::resolved(word, &spaced, None);
1691        let laid = layout.size().width;
1692        assert!((laid - w2).abs() <= 1.0, "{laid} vs {w2}");
1693        // The caret after the last letter is past the spaced word, not the plain one.
1694        let end = layout.caret_rect(word.chars().count()).x;
1695        assert!(end > w0 + 8.0, "the caret ends past the spacing: {end}");
1696    }
1697
1698    /// **Spacing moves the line breaks**: words that fit a box unspaced need a second line
1699    /// spaced, and the lines are cut where the renderer will cut them.
1700    #[test]
1701    fn letter_spacing_moves_the_line_breaks() {
1702        let text = "one two three";
1703        let plain = ResolvedTextStyle::exact(14.0);
1704        let width = measure_resolved(text, &plain).width + 2.0;
1705        assert_eq!(
1706            line_spans_resolved(text, &plain, Some(width), true).len(),
1707            1
1708        );
1709        let spaced = ResolvedTextStyle {
1710            letter_spacing: 3.0,
1711            ..plain
1712        };
1713        assert!(line_spans_resolved(text, &spaced, Some(width), true).len() >= 2);
1714    }
1715
1716    /// **A layout under a resolved style has that style's leading**: the second line of a
1717    /// paragraph set at twice the line height is twice as far down, and the same paragraph
1718    /// laid out by [`TextLayout::wrapped`] — which knows the default alone — puts it where the
1719    /// default does. A selection hit-tested against the wrong one lands on the wrong line.
1720    #[test]
1721    fn a_resolved_layout_takes_the_styles_leading() {
1722        let text = "one two three four five six seven eight";
1723        let open = ResolvedTextStyle {
1724            height: Some(2.0),
1725            ..ResolvedTextStyle::exact(16.0)
1726        };
1727        let styled = TextLayout::resolved(text, &open, Some(90.0));
1728        let plain = TextLayout::wrapped(text, 16.0, FontWeight::Regular, false, Some(90.0));
1729        let spans = line_spans(text, 16.0, FontWeight::Regular, false, Some(90.0), true);
1730        assert!(spans.len() >= 3, "the fixture wraps: {spans:?}");
1731        let second = spans[1].start;
1732        assert_eq!(styled.caret_rect(second).y, 32.0, "two lines of 32 px");
1733        assert_eq!(plain.caret_rect(second).y, line_height(16.0));
1734        assert!(styled.size().height > plain.size().height * 1.5);
1735        // The same style with nothing named is the layout `wrapped` gives.
1736        let closed = TextLayout::resolved(text, &ResolvedTextStyle::exact(16.0), Some(90.0));
1737        assert_eq!(closed.caret_rect(second), plain.caret_rect(second));
1738        assert_eq!(closed.size(), plain.size());
1739    }
1740
1741    /// The spans come back **as the shaper broke them**: each one fits the box, and the
1742    /// words they cover are the words that were written, in order. That is what makes it
1743    /// safe to keep a prefix of the text and drop the rest.
1744    #[test]
1745    fn line_spans_break_where_the_shaper_breaks() {
1746        let text = "one two three four five six seven eight";
1747        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
1748        assert!(spans.len() > 1, "it wrapped: {spans:?}");
1749        let words: Vec<&str> = spans
1750            .iter()
1751            .flat_map(|s| text[s.clone()].split_whitespace())
1752            .collect();
1753        assert_eq!(words, text.split_whitespace().collect::<Vec<_>>());
1754        for span in &spans {
1755            let w = measure_styled(&text[span.clone()], 14.0, FontWeight::Regular, false).width;
1756            assert!(
1757                w <= 80.5,
1758                "each line fits: {:?} at {w}",
1759                &text[span.clone()]
1760            );
1761        }
1762    }
1763
1764    /// The spans are **in order and do not overlap**, which is what lets a caller cut at
1765    /// the start of the first line it is dropping.
1766    #[test]
1767    fn the_spans_run_forwards() {
1768        let text = "one two three four five six seven eight";
1769        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
1770        for pair in spans.windows(2) {
1771            assert!(pair[0].end <= pair[1].start, "{pair:?}");
1772        }
1773    }
1774
1775    /// Without wrapping there is one line however narrow the box: nothing may push a
1776    /// word onto the next one, so the line runs past the edge instead.
1777    #[test]
1778    fn without_wrapping_there_is_one_line() {
1779        let text = "one two three four five six seven eight";
1780        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(40.0), false);
1781        assert_eq!(spans.len(), 1);
1782        assert_eq!(&text[spans[0].clone()], text);
1783    }
1784    use super::*;
1785
1786    #[test]
1787    fn empty_text_has_zero_width() {
1788        let size = measure("", 16.0);
1789        assert_eq!(size.width, 0.0);
1790        assert!(size.height > 0.0);
1791    }
1792
1793    #[test]
1794    fn non_empty_text_has_positive_size() {
1795        let size = measure("Bonjour", 24.0);
1796        assert!(size.width > 0.0, "width = {}", size.width);
1797        assert!(size.height > 0.0, "height = {}", size.height);
1798    }
1799
1800    #[test]
1801    fn rich_runs_measure_mixed_styles() {
1802        use frus_core::Color;
1803        let run = |text: &str, size: f32, weight: FontWeight| TextRun {
1804            text: text.to_string(),
1805            size,
1806            weight,
1807            italic: false,
1808            color: Color::WHITE,
1809            decoration: frus_core::TextDecoration::NONE,
1810            decoration_color: None,
1811            letter_spacing: 0.0,
1812        };
1813        // "normal BOLD" is wider than "normal" alone; the height comes from the
1814        // largest run.
1815        let plain = measure_runs(&[run("normal", 16.0, FontWeight::Regular)]);
1816        let mixed = measure_runs(&[
1817            run("normal", 16.0, FontWeight::Regular),
1818            run(" BOLD", 24.0, FontWeight::Bold),
1819        ]);
1820        assert!(mixed.width > plain.width);
1821        assert!(
1822            mixed.height >= line_height(24.0) - 1.0,
1823            "height driven by the 24px run: {}",
1824            mixed.height
1825        );
1826        // Empty gives a zero size.
1827        assert_eq!(measure_runs(&[]), Size::new(0.0, 0.0));
1828    }
1829
1830    #[test]
1831    fn wrapped_text_grows_taller_within_the_width() {
1832        let text = "a text that is long enough to wrap onto several lines";
1833        let free = measure_wrapped(text, 16.0, FontWeight::Regular, false, None);
1834        let narrow = measure_wrapped(text, 16.0, FontWeight::Regular, false, Some(120.0));
1835        assert!(
1836            narrow.width <= 120.0,
1837            "wrapped within the width: {}",
1838            narrow.width
1839        );
1840        assert!(narrow.height > free.height, "wrapping grows the height");
1841    }
1842
1843    #[test]
1844    fn layout_offsets_are_monotonic_and_match_size() {
1845        let layout = TextLayout::new("Bonjour le monde", 18.0, FontWeight::Regular, false);
1846        let mut prev = -1.0;
1847        for i in 0..=16 {
1848            let x = layout.caret_rect(i).x;
1849            assert!(x >= prev, "offset decreasing at boundary {i}");
1850            prev = x;
1851        }
1852        // The last boundary reaches the natural width.
1853        assert!((layout.caret_rect(16).x - layout.size().width).abs() < 0.5);
1854        // A boundary past the end of the text is clamped.
1855        assert_eq!(layout.caret_rect(99).x, layout.caret_rect(16).x);
1856    }
1857
1858    #[test]
1859    fn hit_test_roundtrips_caret_positions() {
1860        let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
1861        for i in 0..=7 {
1862            let caret = layout.caret_rect(i);
1863            let hit = layout.hit_test(Point::new(caret.x, caret.y + 1.0));
1864            assert_eq!(hit, i, "caret->hit round trip at boundary {i}");
1865        }
1866        // Far to the left or right: the bounds.
1867        assert_eq!(layout.hit_test(Point::new(-100.0, 0.0)), 0);
1868        assert_eq!(layout.hit_test(Point::new(10_000.0, 0.0)), 7);
1869    }
1870
1871    #[test]
1872    fn selection_rects_cover_the_range() {
1873        let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
1874        let rects = layout.selection_rects(2, 5);
1875        assert_eq!(rects.len(), 1);
1876        let r = rects[0];
1877        assert!((r.x - layout.caret_rect(2).x).abs() < 0.01);
1878        assert!((r.x + r.width - layout.caret_rect(5).x).abs() < 0.01);
1879        assert!(r.height > 0.0);
1880        // An empty or inverted range gives no rectangle.
1881        assert!(layout.selection_rects(3, 3).is_empty());
1882        assert!(layout.selection_rects(5, 2).is_empty());
1883    }
1884
1885    #[test]
1886    fn multiline_layout_maps_lines_and_indices() {
1887        // "ab\ncd": boundaries 0..=2 on line 1, 3..=5 on line 2.
1888        let layout = TextLayout::new("ab\ncd", 18.0, FontWeight::Regular, false);
1889        let first = layout.caret_rect(0);
1890        let second = layout.caret_rect(3);
1891        assert!(second.y > first.y, "the 2nd line sits lower");
1892        assert_eq!(second.x, 0.0, "second line starts at x = 0");
1893        // A hit on the second line gives second-line indices.
1894        let hit = layout.hit_test(Point::new(0.0, second.y + 1.0));
1895        assert_eq!(hit, 3);
1896    }
1897
1898    #[test]
1899    fn soft_wrap_indexes_chars_correctly_across_lines() {
1900        // A soft wrap with no `\n`: each word on its own visual line. Indexing must
1901        // stay exact — an index's caret lands on the right line, and the line starts
1902        // are contiguous, with no phantom character at the break.
1903        let text = "aaaa bbbb cccc dddd"; // 19 characters, one word per line at 60px
1904        let layout = TextLayout::wrapped(text, 18.0, FontWeight::Regular, false, Some(60.0));
1905        assert!(
1906            layout.size().height > line_height(18.0) * 2.0,
1907            "several visual lines"
1908        );
1909
1910        // Each word's start: "aaaa"@0, "bbbb"@5, "cccc"@10, "dddd"@15 — each at x
1911        // about 0, the start of its line, on lines of increasing y.
1912        let mut prev_y = -1.0;
1913        for &start in &[0usize, 5, 10, 15] {
1914            let c = layout.caret_rect(start);
1915            assert!(c.x < 1.0, "word start {start} at x about 0 (x={})", c.x);
1916            assert!(c.y > prev_y, "lines of increasing y at {start}");
1917            prev_y = c.y;
1918        }
1919        // A point in the **middle** of a wrapped line round-trips (index 11 is the
1920        // second 'c' of "cccc", clearly not a break boundary).
1921        let c = layout.caret_rect(11);
1922        assert_eq!(layout.hit_test(Point::new(c.x, c.y + 1.0)), 11);
1923        // The last boundary is 19: the three wraps inject no stray +1.
1924        assert_eq!(layout.caret_rect(19).x, layout.caret_rect(99).x);
1925        assert_eq!(layout.caret_rect(19).y, layout.caret_rect(99).y);
1926    }
1927
1928    #[test]
1929    fn empty_layout_keeps_caret_at_origin() {
1930        let layout = TextLayout::new("", 18.0, FontWeight::Regular, false);
1931        let caret = layout.caret_rect(0);
1932        assert_eq!(caret.x, 0.0);
1933        assert!(caret.height > 0.0, "wrapped line height");
1934        assert_eq!(layout.hit_test(Point::new(50.0, 0.0)), 0);
1935    }
1936
1937    /// Reproduces the Android worst case, caught on the device: **no** usable system
1938    /// font at all, only the bundled faces. Shaping must never panic ("no default
1939    /// font found") for **any** weight × italic combination the API can reach.
1940    /// cosmic-text demands an *exact* style and weight match on the primary family:
1941    /// without a bundled oblique face, `.italic()` panicked on the device.
1942    #[test]
1943    #[cfg(all(
1944        feature = "bundled-sans",
1945        feature = "bundled-italic",
1946        feature = "bundled-mono"
1947    ))]
1948    fn embedded_only_font_system_shapes_every_style() {
1949        let mut db = cosmic_text::fontdb::Database::new();
1950        db.load_font_data(DEJAVU_SANS.to_vec());
1951        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
1952        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
1953        db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
1954        db.load_font_data(DEJAVU_MONO.to_vec());
1955        db.set_sans_serif_family(SANS_FAMILY);
1956        db.set_serif_family(SANS_FAMILY);
1957        db.set_cursive_family(SANS_FAMILY);
1958        db.set_fantasy_family(SANS_FAMILY);
1959        db.set_monospace_family(MONO_FAMILY);
1960        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
1961
1962        for weight in [
1963            FontWeight::Regular,
1964            FontWeight::Medium,
1965            FontWeight::SemiBold,
1966            FontWeight::Bold,
1967        ] {
1968            for italic in [false, true] {
1969                let attrs = Attrs::new()
1970                    .weight(Weight(available_weight(weight)))
1971                    .style(if italic { Style::Italic } else { Style::Normal });
1972                let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
1973                buffer.set_size(None, None);
1974                buffer.set_text("Nothing to show", &attrs, Shaping::Advanced, None);
1975                buffer.shape_until_scroll(&mut fs, false); // panics here if broken
1976                let w: f32 = buffer.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
1977                assert!(w > 0.0, "weight {weight:?} italic {italic}: nothing shaped");
1978            }
1979        }
1980    }
1981
1982    /// A scratch font directory, removed when dropped.
1983    struct FontDir(std::path::PathBuf);
1984
1985    impl FontDir {
1986        fn new(tag: &str) -> Self {
1987            let dir = std::env::temp_dir().join(format!("frus-fonts-{tag}-{}", std::process::id()));
1988            let _ = std::fs::remove_dir_all(&dir);
1989            std::fs::create_dir_all(&dir).expect("a scratch font directory");
1990            Self(dir)
1991        }
1992
1993        fn put(&self, name: &str, bytes: &[u8]) {
1994            std::fs::write(self.0.join(name), bytes).expect("a scratch font file");
1995        }
1996    }
1997
1998    impl Drop for FontDir {
1999        fn drop(&mut self) {
2000            let _ = std::fs::remove_dir_all(&self.0);
2001        }
2002    }
2003
2004    /// **Only the emoji faces are taken from the platform's font directory** (milestone
2005    /// 506): a font file named for emoji, and nothing else — not the platform's text
2006    /// faces, which the bundled ones answer for, and not a file that is not a font.
2007    ///
2008    /// Every file here holds a perfectly good face, so a filter that let one through would
2009    /// show as a second face in the database.
2010    #[test]
2011    #[cfg(feature = "bundled-sans")]
2012    fn only_the_emoji_faces_are_taken_from_a_font_directory() {
2013        let dir = FontDir::new("filter");
2014        dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
2015        dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
2016        dir.put("emoji-notes.txt", DEJAVU_SANS);
2017        let mut db = cosmic_text::fontdb::Database::new();
2018        assert_eq!(load_emoji_faces(&mut db, &dir.0), 1, "one file taken");
2019        assert_eq!(db.faces().count(), 1, "and one face in the database");
2020        // A directory that is not there is a platform without one, not an error.
2021        assert_eq!(load_emoji_faces(&mut db, &dir.0.join("absent")), 0);
2022    }
2023
2024    /// **The platform's sans is Roboto's own files** (milestone 626): not its condensed
2025    /// cut, not the emoji face, not a file that is not a font.
2026    #[test]
2027    #[cfg(feature = "bundled-sans")]
2028    fn the_platform_sans_is_robotos_files_and_nothing_else() {
2029        let dir = FontDir::new("platform-sans");
2030        dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
2031        dir.put("Roboto-Bold.ttf", DEJAVU_SANS_BOLD);
2032        dir.put("RobotoCondensed-Regular.ttf", DEJAVU_SANS);
2033        dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
2034        dir.put("roboto-notes.txt", DEJAVU_SANS);
2035        let mut db = cosmic_text::fontdb::Database::new();
2036        assert_eq!(load_platform_sans(&mut db, &dir.0), 2, "two files taken");
2037        assert_eq!(db.faces().count(), 2);
2038        assert_eq!(load_platform_sans(&mut db, &dir.0.join("absent")), 0);
2039    }
2040
2041    /// **A family is asked for by the name a person writes, and found by the one in the
2042    /// file** (milestone 626). The case that started it: an application registered Inter's
2043    /// static files, named "Inter", and drew nothing on Android — the files say
2044    /// "Inter 24pt".
2045    #[test]
2046    fn a_family_name_finds_the_one_inside_the_file() {
2047        let loaded: Vec<String> = ["DejaVu Sans", "DejaVu Sans Mono", "Inter 24pt", "Open Sans"]
2048            .map(String::from)
2049            .to_vec();
2050        let none: Vec<String> = Vec::new();
2051        // Exactly, first.
2052        assert_eq!(
2053            match_family("DejaVu Sans", &loaded, &none),
2054            Some("DejaVu Sans")
2055        );
2056        // Up to case, spaces and hyphens.
2057        assert_eq!(match_family("open-sans", &loaded, &none), Some("Open Sans"));
2058        assert_eq!(match_family("OPENSANS", &loaded, &none), Some("Open Sans"));
2059        // Extended by a word: the file's own name.
2060        assert_eq!(match_family("Inter", &loaded, &none), Some("Inter 24pt"));
2061        assert_eq!(match_family("inter", &loaded, &none), Some("Inter 24pt"));
2062        // Several extensions: the shortest, unless the application's own come first.
2063        assert_eq!(match_family("DejaVu", &loaded, &none), Some("DejaVu Sans"));
2064        let mono = vec!["DejaVu Sans Mono".to_string()];
2065        assert_eq!(
2066            match_family("DejaVu", &loaded, &mono),
2067            Some("DejaVu Sans Mono")
2068        );
2069        // And no further: a name the loaded family only begins, a part of a word, nothing.
2070        assert_eq!(match_family("Inter Tight", &loaded, &none), None);
2071        assert_eq!(match_family("Int", &loaded, &none), None);
2072        assert_eq!(match_family("Roboto", &loaded, &none), None);
2073    }
2074
2075    /// **The weight drawn is the nearest one loaded, by the web's rule** (milestone 626).
2076    #[test]
2077    fn a_weight_snaps_to_the_nearest_loaded_by_the_webs_rule() {
2078        let bundled = [(400, 400), (700, 700)];
2079        // The bundled sans: the old 400-or-700 answers, unchanged.
2080        assert_eq!(nearest_weight(400, &bundled), 400);
2081        assert_eq!(nearest_weight(500, &bundled), 400);
2082        assert_eq!(nearest_weight(600, &bundled), 700);
2083        assert_eq!(nearest_weight(300, &bundled), 400);
2084        assert_eq!(nearest_weight(900, &bundled), 700);
2085        // An application's four static faces are all used.
2086        let four = [(400, 400), (500, 500), (600, 600), (700, 700)];
2087        for weight in [400, 500, 600, 700] {
2088            assert_eq!(nearest_weight(weight, &four), weight);
2089        }
2090        // 400 to 500 look heavier up to 500 first, then lighter.
2091        assert_eq!(nearest_weight(400, &[(300, 300), (500, 500)]), 500);
2092        assert_eq!(nearest_weight(450, &[(300, 300), (600, 600)]), 300);
2093        // Below 400 lighter first; above 500 heavier first.
2094        assert_eq!(nearest_weight(350, &[(300, 300), (400, 400)]), 300);
2095        assert_eq!(nearest_weight(550, &[(500, 500), (600, 600)]), 600);
2096        // A variable face draws every weight its axis spans, and its ends outside it.
2097        assert_eq!(nearest_weight(650, &[(100, 900)]), 650);
2098        assert_eq!(nearest_weight(950, &[(100, 900)]), 900);
2099        // Nothing known: the weight as asked.
2100        assert_eq!(nearest_weight(500, &[]), 500);
2101    }
2102
2103    /// **The inventory reads what a database holds** — and says when default text would
2104    /// have nothing to be drawn in, the cue Android takes to load its own sans.
2105    #[test]
2106    #[cfg(all(feature = "bundled-sans", feature = "bundled-italic"))]
2107    fn the_inventory_reads_the_faces_loaded() {
2108        assert_eq!(families_in(DEJAVU_SANS), vec!["DejaVu Sans".to_string()]);
2109        assert!(families_in(b"not a font").is_empty());
2110
2111        let mut db = cosmic_text::fontdb::Database::new();
2112        db.load_font_data(DEJAVU_SANS.to_vec());
2113        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
2114        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
2115        let mut loaded = Loaded::of(&db);
2116        loaded.app.clear();
2117        assert_eq!(loaded.text, vec!["DejaVu Sans".to_string()]);
2118        assert_eq!(loaded.slanted, vec!["DejaVu Sans".to_string()]);
2119        assert_eq!(weights_of(&db, "DejaVu Sans"), vec![(400, 400), (700, 700)]);
2120        assert!(weights_of(&db, "Inter").is_empty());
2121
2122        // fontdb's generic sans is a name nobody loaded here, as on Android.
2123        assert!(!loaded.generic_sans);
2124        assert!(
2125            !loaded.wants_platform_sans(Some("DejaVu")),
2126            "a name it plainly means"
2127        );
2128        assert!(
2129            loaded.wants_platform_sans(Some("Inter")),
2130            "a name nothing answers to"
2131        );
2132        assert!(
2133            loaded.wants_platform_sans(None),
2134            "no name, and no generic either"
2135        );
2136        // Nothing the name means — but a face of the application's own is a better
2137        // answer than the platform's, and it is the one drawn.
2138        loaded.app = vec!["DejaVu Sans".to_string()];
2139        assert!(!loaded.wants_platform_sans(Some("Inter")));
2140        assert_eq!(loaded.fallback(), Some("DejaVu Sans"));
2141    }
2142
2143    /// **A misspelt family is drawn in the face it means**, in the database Android is left
2144    /// with: no system font, so no fallback list behind a name that resolves to nothing.
2145    /// Shaping in the name `match_family` found gives real glyphs from that face.
2146    #[test]
2147    #[cfg(feature = "bundled-sans")]
2148    fn a_family_found_by_its_plain_name_draws_real_glyphs() {
2149        let mut db = cosmic_text::fontdb::Database::new();
2150        db.load_font_data(DEJAVU_SANS.to_vec());
2151        let face = db.faces().next().map(|face| face.id).expect("the face");
2152        let loaded = Loaded::of(&db);
2153        let family = match_family("dejavu", &loaded.families, &[]).expect("found");
2154        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2155        let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
2156        buffer.set_size(None, None);
2157        let attrs = Attrs::new().family(cosmic_text::Family::Name(family));
2158        buffer.set_text("Hello", &attrs, Shaping::Advanced, None);
2159        buffer.shape_until_scroll(&mut fs, false);
2160        let glyphs: Vec<_> = buffer
2161            .layout_runs()
2162            .flat_map(|run| run.glyphs.iter())
2163            .map(|glyph| (glyph.font_id, glyph.glyph_id))
2164            .collect();
2165        assert_eq!(glyphs.len(), 5);
2166        assert!(glyphs
2167            .iter()
2168            .all(|&(font, glyph)| font == face && glyph != 0));
2169    }
2170
2171    /// **An emoji is drawn from the emoji face** when the run's own font lacks it, in the
2172    /// arrangement Android is left with: the bundled faces, no system font, and the emoji
2173    /// face loaded on its own. The glyph comes from that face and is a real one — on the
2174    /// device it was an empty box.
2175    ///
2176    /// It needs a colour emoji font to load, and Windows ships one; elsewhere there is
2177    /// nothing to load, and the test says so and passes.
2178    #[test]
2179    #[cfg(feature = "bundled-sans")]
2180    fn an_emoji_is_drawn_from_the_emoji_face_the_runs_font_lacks() {
2181        let emoji = std::path::Path::new("C:\\Windows\\Fonts\\seguiemj.ttf");
2182        if !emoji.exists() {
2183            eprintln!("no colour emoji font at {}; skipped", emoji.display());
2184            return;
2185        }
2186        let mut db = cosmic_text::fontdb::Database::new();
2187        db.load_font_data(DEJAVU_SANS.to_vec());
2188        db.load_font_file(emoji).expect("the emoji font");
2189        db.set_sans_serif_family(SANS_FAMILY);
2190        let emoji_face = db
2191            .faces()
2192            .find(|face| face.post_script_name.contains("Emoji"))
2193            .map(|face| face.id)
2194            .expect("an emoji face");
2195        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2196
2197        let text = "Hi \u{1F44B}";
2198        let at = text.find('\u{1F44B}').expect("the wave");
2199        let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2200        buffer.set_size(None, None);
2201        buffer.set_text(
2202            text,
2203            &Attrs::new().family(family_for(text)),
2204            Shaping::Advanced,
2205            None,
2206        );
2207        buffer.shape_until_scroll(&mut fs, false);
2208        let (font, glyph) = buffer
2209            .layout_runs()
2210            .flat_map(|run| run.glyphs.iter())
2211            .find(|glyph| glyph.start == at)
2212            .map(|glyph| (glyph.font_id, glyph.glyph_id))
2213            .expect("a glyph for the emoji");
2214        assert_eq!(font, emoji_face, "the emoji comes from the emoji face");
2215        assert_ne!(glyph, 0, "and is a real glyph, not the empty box");
2216    }
2217
2218    /// Reproduces the Android Arabic case **exactly**: the bundled db alone, with no
2219    /// system font and therefore no platform fallback list, with the Noto Naskh face
2220    /// loaded. `family_for` must route the Arabic run to the Naskh family, and shaping
2221    /// must produce **real** glyphs (non-zero ids), not `.notdef`. If `Family::Name`
2222    /// fails to resolve here, the glyphs come out empty — the blank seen on the
2223    /// device.
2224    #[test]
2225    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2226    fn arabic_shapes_with_embedded_only_font_system() {
2227        let mut db = cosmic_text::fontdb::Database::new();
2228        db.load_font_data(DEJAVU_SANS.to_vec());
2229        db.load_font_data(NOTO_ARABIC.to_vec());
2230        db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
2231        db.set_sans_serif_family(SANS_FAMILY);
2232        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2233
2234        let text = "مهامي";
2235        let attrs = Attrs::new().family(family_for(text));
2236        let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2237        buffer.set_size(None, None);
2238        buffer.set_text(text, &attrs, Shaping::Advanced, None);
2239        buffer.shape_until_scroll(&mut fs, false);
2240
2241        let mut glyphs = 0usize;
2242        let mut real = 0usize; // glyphs whose glyph_id != 0, so not .notdef
2243        for run in buffer.layout_runs() {
2244            for g in run.glyphs.iter() {
2245                glyphs += 1;
2246                if g.glyph_id != 0 {
2247                    real += 1;
2248                }
2249            }
2250        }
2251        assert!(glyphs > 0, "no glyph shaped for Arabic");
2252        assert!(
2253            real > 0,
2254            "only .notdef ({glyphs} glyphs, 0 real): Family::Name(\"{ARABIC_FAMILY}\") did not resolve the Naskh face"
2255        );
2256    }
2257
2258    /// A positioning diagnosis: an RTL run in a **wide** buffer (width = the surface)
2259    /// gets **right-aligned** by cosmic-text, so the glyphs land near the right edge
2260    /// (x about the width) and therefore off-screen once shifted by `position.x`.
2261    /// With no width constraint (`None`) they start at x about 0. This is the cause
2262    /// of the blank Arabic text on the device.
2263    #[test]
2264    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2265    fn rtl_right_aligns_to_buffer_width() {
2266        let mut db = cosmic_text::fontdb::Database::new();
2267        db.load_font_data(DEJAVU_SANS.to_vec());
2268        db.load_font_data(NOTO_ARABIC.to_vec());
2269        db.set_sans_serif_family(SANS_FAMILY);
2270        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2271        let text = "العربية";
2272        let attrs = Attrs::new().family(family_for(text));
2273
2274        let mut first_glyph_x = |width: Option<f32>| {
2275            let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2276            buffer.set_size(width, Some(200.0));
2277            buffer.set_text(text, &attrs, Shaping::Advanced, None);
2278            buffer.shape_until_scroll(&mut fs, false);
2279            buffer
2280                .layout_runs()
2281                .flat_map(|r| r.glyphs.iter().map(|g| g.x))
2282                .fold(f32::MAX, f32::min)
2283        };
2284
2285        let wide = first_glyph_x(Some(1080.0));
2286        let free = first_glyph_x(None);
2287        assert!(wide > 500.0, "a wide RTL run should push right (x={wide})");
2288        assert!(
2289            free < 50.0,
2290            "an unconstrained RTL run should start left (x={free})"
2291        );
2292    }
2293
2294    #[test]
2295    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2296    fn arabic_falls_back_to_the_embedded_naskh_face() {
2297        // DejaVu does not cover Arabic: the bundled fallback (Noto Naskh) has to take
2298        // over and **shape** the glyphs, giving a non-zero, sensible width. A missing
2299        // fallback would give 0, or .notdef glyphs.
2300        let hello = "مرحبا بالعالم"; // "hello world"
2301        let m = measure(hello, 24.0);
2302        assert!(m.width > 60.0, "Arabic must shape (width {})", m.width);
2303        assert!(m.height > 0.0);
2304
2305        // The fallback does not trample Latin: "Hello" keeps a coherent width.
2306        let latin = measure("Hello", 24.0);
2307        assert!(latin.width > 0.0);
2308
2309        // Mixed bidi (Arabic plus Latin digits) is measured as one piece, without
2310        // panicking; cosmic-text reorders internally.
2311        let mixed = measure("قيمة 42 نقطة", 24.0);
2312        assert!(mixed.width > 0.0, "mixed bidi text was not shaped");
2313    }
2314
2315    #[test]
2316    fn weights_snap_to_embedded_faces() {
2317        // A weight with no exact face (Medium 500) MUST fall back to a bundled face —
2318        // otherwise cosmic-text switches to platform fallback lists, which do not
2319        // exist on Android (a panic on the device).
2320        assert_eq!(available_weight(FontWeight::Regular), 400);
2321        assert_eq!(available_weight(FontWeight::Medium), 400);
2322        assert_eq!(available_weight(FontWeight::SemiBold), 700);
2323        assert_eq!(available_weight(FontWeight::Bold), 700);
2324        // And shaping is deterministic: Medium measures like Regular (the same face),
2325        // and SemiBold like Bold.
2326        let text = "Titre de section";
2327        let regular = measure_styled(text, 20.0, FontWeight::Regular, false);
2328        let medium = measure_styled(text, 20.0, FontWeight::Medium, false);
2329        assert_eq!(medium.width, regular.width);
2330        let semibold = measure_styled(text, 20.0, FontWeight::SemiBold, false);
2331        let bold = measure_styled(text, 20.0, FontWeight::Bold, false);
2332        assert_eq!(semibold.width, bold.width);
2333        assert!(bold.width > regular.width);
2334    }
2335
2336    /// The natural width is a **whole** number, and never less than what the text
2337    /// needs. The layout engine rounds the boxes it hands out to whole pixels, so a
2338    /// measurement of 146.4 becomes a box of 146 — and the text, shaped again at 146
2339    /// when it is painted, wraps onto a line the layout never reserved.
2340    #[test]
2341    fn the_natural_width_is_never_rounded_down_below_the_text() {
2342        for text in ["Write code", "Bonjour le monde", "A", "iiiii"] {
2343            for size in [12.0_f32, 15.0, 20.0, 24.0] {
2344                let natural = measure_styled(text, size, FontWeight::Bold, false);
2345                assert_eq!(
2346                    natural.width,
2347                    natural.width.ceil(),
2348                    "a whole number for {text:?} at {size}: {}",
2349                    natural.width
2350                );
2351                // Given exactly that width, the text still fits on one line.
2352                let at_its_width =
2353                    measure_wrapped(text, size, FontWeight::Bold, false, Some(natural.width));
2354                assert_eq!(
2355                    at_its_width.height, natural.height,
2356                    "{text:?} at {size} wrapped inside its own width"
2357                );
2358            }
2359        }
2360    }
2361
2362    /// **And the height, which milestone 289 left fractional.** It fixed the axis the
2363    /// wrapping bug presented on and no more: a line height is a fraction of a size —
2364    /// 14.4 for a 12 px line — so a two-line paragraph measured itself at 28.8 and, at a
2365    /// top edge that rounded the other way, was handed 28.
2366    ///
2367    /// The same bug, in the same function, on the axis nobody looked at. It was found by
2368    /// the rule this milestone put in rather than by a screen, which is the argument for
2369    /// having the rule (issue #54).
2370    #[test]
2371    fn the_natural_height_is_a_whole_number_too() {
2372        for text in ["Write code", "one two three four five six seven eight", "A"] {
2373            for size in [12.0_f32, 15.0, 20.0, 24.0] {
2374                for width in [None, Some(60.0), Some(120.0)] {
2375                    let measured = measure_wrapped(text, size, FontWeight::Bold, false, width);
2376                    assert_eq!(
2377                        measured.height,
2378                        measured.height.ceil(),
2379                        "a whole number for {text:?} at {size} in {width:?}: {}",
2380                        measured.height
2381                    );
2382                }
2383            }
2384        }
2385        // An empty label reserves a whole line as well: it is where a caret goes, and
2386        // where text put there later has to fit.
2387        let empty = measure_styled("", 16.0, FontWeight::Regular, false);
2388        assert_eq!(empty.height, empty.height.ceil(), "{}", empty.height);
2389        assert!(empty.height >= line_height(16.0));
2390    }
2391
2392    /// Under a constraint the ceiling is clamped back to it: a box wider than allowed
2393    /// is a different bug from the one above.
2394    #[test]
2395    fn a_constrained_measurement_never_exceeds_its_constraint() {
2396        let measured = measure_wrapped(
2397            "A rather long sentence that has to wrap somewhere",
2398            18.0,
2399            FontWeight::Regular,
2400            false,
2401            Some(120.0),
2402        );
2403        assert!(measured.width <= 120.0, "{}", measured.width);
2404    }
2405
2406    /// Italic text measures whatever faces are bundled. This is the guard on the
2407    /// promise that dropping `bundled-italic` costs slanted text and not text: asking
2408    /// cosmic-text for a style it has no face for used to reach the platform fallback
2409    /// lists, which are empty on Android, and panic there.
2410    #[test]
2411    fn italic_measures_whether_or_not_an_oblique_face_is_bundled() {
2412        let measured = measure_styled("Slanted", 16.0, FontWeight::Regular, true);
2413        assert!(measured.width > 0.0, "nothing shaped");
2414    }
2415
2416    /// A style is only ever *asked for* when the database can answer it — the whole
2417    /// point of [`available_style`], and true in either configuration.
2418    #[test]
2419    fn italic_is_only_asked_for_when_a_face_can_answer() {
2420        // Measuring is what builds the font system, which is what reads the database.
2421        let _ = measure("x", 12.0);
2422        assert_eq!(
2423            available_style(false),
2424            Style::Normal,
2425            "upright asked for italic"
2426        );
2427        assert_eq!(
2428            available_style(true) == Style::Italic,
2429            ITALIC.load(Ordering::Relaxed),
2430            "italic asked for without a face to answer it"
2431        );
2432    }
2433
2434    #[test]
2435    fn bold_measures_wider_than_regular() {
2436        // The bundled bold face must actually be chosen: bold is wider than regular
2437        // at the same size.
2438        let regular = measure_styled("Bonjour le monde", 24.0, FontWeight::Regular, false);
2439        let bold = measure_styled("Bonjour le monde", 24.0, FontWeight::Bold, false);
2440        assert!(
2441            bold.width > regular.width,
2442            "gras {} <= normal {}",
2443            bold.width,
2444            regular.width
2445        );
2446    }
2447
2448    /// The cache must be invisible: measuring twice gives the same answer as measuring
2449    /// once, whichever entry point asked, and under a constraint as well as free.
2450    #[test]
2451    fn a_cached_measurement_is_the_measurement() {
2452        for (text, size) in [("Open", 15.0_f32), ("Task number 42 — due Friday", 13.0)] {
2453            let first = measure(text, size);
2454            let second = measure(text, size);
2455            assert_eq!(
2456                first, second,
2457                "{text:?} measured differently the second time"
2458            );
2459
2460            let styled = measure_styled(text, size, FontWeight::Bold, false);
2461            assert_eq!(
2462                styled,
2463                measure_styled(text, size, FontWeight::Bold, false),
2464                "{text:?} bold measured differently the second time"
2465            );
2466
2467            let wrapped = measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0));
2468            assert_eq!(
2469                wrapped,
2470                measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0)),
2471                "{text:?} wrapped measured differently the second time"
2472            );
2473            // The constraint is part of the key: a different width is a different
2474            // answer, not a hit on the free one.
2475            assert!(
2476                wrapped.height >= first.height,
2477                "wrapping to 60 px should not make {text:?} shorter"
2478            );
2479        }
2480    }
2481
2482    /// A retired generation must not lose an entry that is still being asked for:
2483    /// enough distinct strings to rotate the cache several times over, with one string
2484    /// re-measured throughout, which has to keep the same answer.
2485    #[test]
2486    fn a_string_still_in_use_survives_the_rotation() {
2487        let kept = measure("still here", 14.0);
2488        for i in 0..(CACHE_CAP * 2 + 64) {
2489            measure(&format!("filler {i}"), 14.0);
2490            if i % 512 == 0 {
2491                assert_eq!(kept, measure("still here", 14.0), "lost at {i}");
2492            }
2493        }
2494        assert_eq!(kept, measure("still here", 14.0));
2495    }
2496
2497    /// Registering a face changes what text can measure to, so every remembered
2498    /// answer has to go. The measurement itself must still work afterwards.
2499    #[test]
2500    fn registering_a_font_forgets_what_was_measured() {
2501        let before = measure("forget me", 15.0);
2502        forget_measurements();
2503        let after = measure("forget me", 15.0);
2504        assert_eq!(before, after, "the same faces must measure the same");
2505    }
2506    /// A baseline sits inside its line box, below the top and above the bottom — and
2507    /// well above the middle, because most of a face is above the baseline.
2508    #[test]
2509    fn a_baseline_sits_where_a_line_of_text_does() {
2510        let size = 20.0;
2511        let b = baseline(size, FontWeight::Regular, false);
2512        let line = line_height(size);
2513        assert!(b > 0.0 && b < line, "inside the line box: {b} of {line}");
2514        assert!(b > line * 0.5, "and below its middle: {b} of {line}");
2515    }
2516
2517    /// It scales with the size, which is the whole reason two sizes cannot be aligned
2518    /// by their tops.
2519    #[test]
2520    fn a_bigger_face_has_a_lower_baseline() {
2521        let small = baseline(12.0, FontWeight::Regular, false);
2522        let large = baseline(24.0, FontWeight::Regular, false);
2523        assert!(large > small * 1.5, "{small} then {large}");
2524    }
2525
2526    /// Runs sharing a line share the **largest** baseline: the tallest ascender is
2527    /// what decides where the line sits.
2528    #[test]
2529    fn mixed_runs_take_the_tallest_baseline() {
2530        let run = |text: &str, size: f32| TextRun {
2531            text: text.into(),
2532            size,
2533            weight: FontWeight::Regular,
2534            italic: false,
2535            color: frus_core::Color::WHITE,
2536            decoration: frus_core::TextDecoration::default(),
2537            decoration_color: None,
2538            letter_spacing: 0.0,
2539        };
2540        let runs = vec![run("small", 12.0), run("large", 24.0)];
2541        let mixed = baseline_of_runs(&runs).expect("two runs");
2542        assert!((mixed - baseline(24.0, FontWeight::Regular, false)).abs() < 0.01);
2543    }
2544
2545    /// **A taller line makes a taller measurement**, and by exactly the ratio asked for.
2546    ///
2547    /// This is the assertion that matters: the renderer lays a paragraph out with
2548    /// `Metrics::new(size, size * height)`, and if the measurement did not use the same
2549    /// number the layout would reserve room for lines that land somewhere else.
2550    #[test]
2551    fn a_named_line_height_reaches_the_measurement() {
2552        let words = "one two three four five six seven eight nine ten";
2553        let plain = ResolvedTextStyle::exact(16.0);
2554        let open = ResolvedTextStyle {
2555            height: Some(2.4),
2556            ..plain
2557        };
2558        // Wrapped to a narrow column, so there are several lines to stack.
2559        let a = measure_wrapped_resolved(words, &plain, Some(80.0));
2560        let b = measure_wrapped_resolved(words, &open, Some(80.0));
2561        assert!(a.height > 0.0 && b.height > 0.0);
2562        assert_eq!(
2563            a.width, b.width,
2564            "the line height changes the stacking, never the letters"
2565        );
2566        let ratio = b.height / a.height;
2567        assert!(
2568            (ratio - 2.0).abs() < 0.01,
2569            "doubling the line height doubles the block: {ratio}"
2570        );
2571    }
2572
2573    /// The measurement cache is keyed on the line height too. Without that, the same words
2574    /// at two heights would share one answer and the second would be silently wrong.
2575    #[test]
2576    fn two_line_heights_do_not_share_a_cached_answer() {
2577        let words = "cached words that wrap across a couple of lines here";
2578        let packed = ResolvedTextStyle {
2579            height: Some(1.0),
2580            ..ResolvedTextStyle::exact(14.0)
2581        };
2582        let open = ResolvedTextStyle {
2583            height: Some(2.0),
2584            ..ResolvedTextStyle::exact(14.0)
2585        };
2586        let first = measure_wrapped_resolved(words, &packed, Some(90.0));
2587        let second = measure_wrapped_resolved(words, &open, Some(90.0));
2588        // Asked again, in the other order, to catch a cache that answered from the wrong
2589        // entry rather than one that simply never filled.
2590        assert_eq!(measure_wrapped_resolved(words, &open, Some(90.0)), second);
2591        assert_eq!(measure_wrapped_resolved(words, &packed, Some(90.0)), first);
2592        assert!(second.height > first.height);
2593    }
2594
2595    /// A one-line box floor follows the style's line height, not the size alone.
2596    #[test]
2597    fn a_line_box_follows_the_height_it_was_given() {
2598        let open = ResolvedTextStyle {
2599            height: Some(3.0),
2600            ..ResolvedTextStyle::exact(16.0)
2601        };
2602        assert_eq!(line_box(32.0, &ResolvedTextStyle::exact(16.0), 0.0), 32.0);
2603        assert_eq!(
2604            line_box(32.0, &open, 0.0),
2605            48.0,
2606            "the content wins over the floor"
2607        );
2608    }
2609
2610    /// A named family reaches the shaping, and a **different face measures differently** —
2611    /// which is the whole reason a style may name one.
2612    #[test]
2613    fn a_named_family_reaches_the_measurement() {
2614        let words = "The quick brown fox";
2615        let plain = ResolvedTextStyle::exact(16.0);
2616        let mono = ResolvedTextStyle {
2617            family: Some(frus_core::FontFamily::Monospace),
2618            ..plain
2619        };
2620        let a = measure_wrapped_resolved(words, &plain, None);
2621        let b = measure_wrapped_resolved(words, &mono, None);
2622        assert!(a.width > 0.0 && b.width > 0.0);
2623        assert_ne!(
2624            a.width, b.width,
2625            "a monospaced face sets these words to a different width"
2626        );
2627    }
2628
2629    /// **Arabic keeps its face even when a family is named.**
2630    ///
2631    /// Not a hedge: cosmic-text does not fall back across families on Android, where the
2632    /// platform fallback lists are empty, so a family without Arabic coverage draws
2633    /// nothing at all. Text in an unexpected face is a smaller failure than a blank
2634    /// screen. The measurement has to make the same choice the renderer will, so the rule
2635    /// lives in one function that both call.
2636    #[test]
2637    fn arabic_keeps_its_face_whatever_was_named() {
2638        let arabic = "\u{0645}\u{0631}\u{062d}\u{0628}\u{0627}";
2639        let named = family_for_style(arabic, Some(frus_core::FontFamily::Monospace));
2640        assert_eq!(
2641            format!("{named:?}"),
2642            format!("{:?}", family_for(arabic)),
2643            "the script wins over the name"
2644        );
2645        // And a Latin run in the same style is free to take the name.
2646        let latin = family_for_style("hello", Some(frus_core::FontFamily::Monospace));
2647        assert_eq!(format!("{latin:?}"), format!("{:?}", monospace_family()));
2648    }
2649
2650    /// Two families do not share a cached measurement, for the same reason two line
2651    /// heights do not: the answer is different and the words are the same.
2652    #[test]
2653    fn two_families_do_not_share_a_cached_answer() {
2654        let words = "shared words in two faces";
2655        let plain = ResolvedTextStyle::exact(15.0);
2656        let mono = ResolvedTextStyle {
2657            family: Some(frus_core::FontFamily::Monospace),
2658            ..plain
2659        };
2660        let first = measure_wrapped_resolved(words, &plain, None);
2661        let second = measure_wrapped_resolved(words, &mono, None);
2662        // Asked again in the other order, to catch a cache answering from the wrong entry
2663        // rather than one that simply never filled.
2664        assert_eq!(measure_wrapped_resolved(words, &mono, None), second);
2665        assert_eq!(measure_wrapped_resolved(words, &plain, None), first);
2666        assert_ne!(first.width, second.width);
2667    }
2668}