Skip to main content

text_typeset/
font_service.rs

1//! Shared font service: the part of text-typeset that can be shared
2//! across many widgets viewing many documents.
3//!
4//! A [`TextFontService`] owns four things:
5//!
6//! - a font registry (parsed faces, family lookup, fallback chain),
7//! - a GPU-bound glyph atlas (RGBA texture with bucketed allocations),
8//! - a glyph cache keyed on `(face, glyph_id, physical_size_px)`,
9//! - a `swash` scale context (reusable rasterizer workspace).
10//!
11//! None of these describe **what** a specific widget is showing — they
12//! describe **how** glyphs are rasterized and cached. Two widgets
13//! viewing the same or different documents in the same window should
14//! share one `TextFontService` so that:
15//!
16//! 1. every glyph for a given `(face, size)` lives in one atlas
17//!    and is uploaded to the GPU exactly once per frame;
18//! 2. every shaped glyph rasterization happens at most once,
19//!    amortized over every widget that ever renders it;
20//! 3. font registration and fallback resolution are consistent
21//!    across the whole UI.
22//!
23//! Per-widget state — viewport, zoom, scroll offset, flow layout,
24//! cursor, colors — lives on a separate [`DocumentFlow`] that borrows
25//! the service at layout and render time.
26//!
27//! [`DocumentFlow`]: crate::DocumentFlow
28//!
29//! # HiDPI invalidation
30//!
31//! [`set_scale_factor`](TextFontService::set_scale_factor) is the one
32//! mutation that invalidates existing work: cached glyphs were
33//! rasterized at the old physical ppem and are wrong at the new one,
34//! and flow layouts stored shaped advances that depended on the
35//! previous ppem rounding. The service clears its own glyph cache
36//! and atlas on the spot, but it cannot reach into per-widget
37//! [`DocumentFlow`] instances. Instead it bumps a monotonic
38//! `scale_generation` counter every time the scale factor changes.
39//! Each `DocumentFlow` remembers the generation it was last laid out
40//! at. Call [`crate::DocumentFlow::layout_dirty_for_scale`] from the
41//! framework side to ask "does this flow need a relayout?" and re-run
42//! `layout_full` when the answer is yes.
43
44use crate::atlas::allocator::GlyphAtlas;
45use crate::atlas::cache::GlyphCache;
46use crate::font::hinted::GlyphRendering;
47use crate::font::registry::FontRegistry;
48use crate::font::resolve::resolve_font;
49use crate::shaping::shaper::font_metrics_px;
50use crate::types::{FontFaceId, TextFormat};
51
52/// Outcome of a call to [`TextFontService::atlas_snapshot`].
53///
54/// Bundles the four signals a framework adapter needs to upload
55/// (or skip uploading) the glyph atlas texture to the GPU:
56///
57/// - whether the atlas has pending pixel changes since the last
58///   snapshot,
59/// - its current pixel dimensions,
60/// - a borrow of the raw RGBA pixel buffer, and
61/// - whether any cached glyphs were evicted during this snapshot —
62///   a signal that callers with paint caches holding old atlas
63///   UVs must treat as an invalidation even if the atlas itself
64///   reports clean afterwards (evicted slots may be reused by
65///   future allocations, so any cached UV pointing into them is
66///   stale).
67///
68/// Exposed as a struct rather than a tuple so every caller names
69/// fields explicitly and can't swap positions silently.
70#[derive(Debug)]
71#[non_exhaustive]
72pub struct AtlasSnapshot<'a> {
73    /// True if the atlas texture has pending pixel changes
74    /// since it was last marked clean. The snapshot call clears
75    /// this flag, so the caller must either upload `pixels` now
76    /// or accept a one-frame delay.
77    pub dirty: bool,
78    /// Current atlas texture width in pixels.
79    pub width: u32,
80    /// Current atlas texture height in pixels.
81    pub height: u32,
82    /// Raw RGBA8 pixel buffer backing the atlas texture.
83    pub pixels: &'a [u8],
84    /// True if eviction freed at least one glyph slot during
85    /// this snapshot. Callers that cache glyph positions (e.g.
86    /// framework paint caches indexed by layout key) must
87    /// invalidate when this is true — evicted slots may be
88    /// reused by future allocations and old UVs would then
89    /// point to the wrong glyph.
90    pub glyphs_evicted: bool,
91}
92
93/// Shared font resources for a text-typeset session.
94///
95/// Owns the font registry, the glyph atlas, the glyph cache, and the
96/// `swash` scale context. Construct one per process (or one per window
97/// if you really need isolated atlases) and share it by `Rc<RefCell<_>>`
98/// across every [`DocumentFlow`] that renders into the same atlas.
99///
100/// [`DocumentFlow`]: crate::DocumentFlow
101pub struct TextFontService {
102    pub(crate) font_registry: FontRegistry,
103    pub(crate) atlas: GlyphAtlas,
104    pub(crate) glyph_cache: GlyphCache,
105    pub(crate) scale_context: swash::scale::ScaleContext,
106    pub(crate) scale_factor: f32,
107    /// Bumps every time [`set_scale_factor`](Self::set_scale_factor)
108    /// actually changes the value. `DocumentFlow` snapshots this on
109    /// layout and exposes a dirty check for callers.
110    pub(crate) scale_generation: u64,
111    /// Monotonic counter bumped every time the atlas loses entries
112    /// (LRU eviction or full reset on scale-factor change). Per-widget
113    /// `DocumentFlow`s stamp this on every full `render()` and refuse
114    /// to reuse their cached glyph quads (cursor-only / block-only
115    /// paint paths) when the service's current epoch differs — at
116    /// that point any baked-in atlas pixel coordinates in those
117    /// cached quads may reference slots now owned by unrelated
118    /// glyphs.
119    pub(crate) eviction_epoch: u64,
120}
121
122impl TextFontService {
123    /// Create a service whose font registry is pre-populated with the
124    /// operating system's fonts, so arbitrary documents (CJK, emoji,
125    /// scripts the host didn't bundle) still render via glyph fallback.
126    ///
127    /// Still call [`set_default_font`](Self::set_default_font) (and
128    /// usually [`register_font`](Self::register_font) for the primary
129    /// UI font) before any [`DocumentFlow`] lays out content.
130    ///
131    /// Enumerating OS fonts is a one-time startup cost; their bytes load
132    /// lazily on first use. Use
133    /// [`new_without_system_fonts`](Self::new_without_system_fonts) to
134    /// skip the scan and keep a fully host-controlled font set.
135    ///
136    /// [`DocumentFlow`]: crate::DocumentFlow
137    pub fn new() -> Self {
138        Self::with_registry(FontRegistry::new())
139    }
140
141    /// Like [`new`](Self::new) but with no OS font enumeration: only
142    /// fonts added via `register_font*` are available. Use this when the
143    /// host ships a controlled font set and wants neither the startup
144    /// scan nor implicit system fonts.
145    pub fn new_without_system_fonts() -> Self {
146        Self::with_registry(FontRegistry::new_without_system_fonts())
147    }
148
149    fn with_registry(font_registry: FontRegistry) -> Self {
150        Self {
151            font_registry,
152            atlas: GlyphAtlas::new(),
153            glyph_cache: GlyphCache::new(),
154            scale_context: swash::scale::ScaleContext::new(),
155            scale_factor: 1.0,
156            scale_generation: 0,
157            eviction_epoch: 0,
158        }
159    }
160
161    // ── Font registration ───────────────────────────────────────
162
163    /// Register a font face from raw TTF/OTF/WOFF bytes.
164    ///
165    /// Parses the font's name table to extract family, weight, and
166    /// style, then indexes it via `fontdb` for CSS-spec font matching.
167    /// Returns the first face ID — font collections (`.ttc`) may
168    /// contain multiple faces.
169    ///
170    /// # Panics
171    ///
172    /// Panics if the font data contains no parseable faces.
173    pub fn register_font(&mut self, data: &[u8]) -> FontFaceId {
174        let ids = self.font_registry.register_font(data);
175        ids.into_iter()
176            .next()
177            .expect("font data contained no faces")
178    }
179
180    /// Register a font from a pre-built shared byte container,
181    /// avoiding the copy that [`register_font`](Self::register_font)
182    /// would perform.
183    ///
184    /// Pass an `Arc<Mmap>` (or any `Arc<dyn AsRef<[u8]> + Sync + Send>`)
185    /// when the caller already holds the data in a shareable form —
186    /// useful for large system fonts (color emoji) where copying to an
187    /// owned `Vec<u8>` would double the resident memory cost.
188    ///
189    /// # Panics
190    ///
191    /// Panics if the font data contains no parseable faces.
192    pub fn register_font_shared(&mut self, data: crate::font::SharedFontData) -> FontFaceId {
193        let ids = self.font_registry.register_font_shared(data);
194        ids.into_iter()
195            .next()
196            .expect("font data contained no faces")
197    }
198
199    /// Register a font with explicit metadata, overriding the font's
200    /// name table. Use when the font's internal metadata is unreliable
201    /// or when aliasing a font to a different family name.
202    ///
203    /// # Panics
204    ///
205    /// Panics if the font data contains no parseable faces.
206    pub fn register_font_as(
207        &mut self,
208        data: &[u8],
209        family: &str,
210        weight: u16,
211        italic: bool,
212    ) -> FontFaceId {
213        let ids = self
214            .font_registry
215            .register_font_as(data, family, weight, italic);
216        ids.into_iter()
217            .next()
218            .expect("font data contained no faces")
219    }
220
221    /// Like [`register_font_as`](Self::register_font_as) but takes a
222    /// pre-built shared byte container, avoiding the copy.
223    ///
224    /// # Panics
225    ///
226    /// Panics if the font data contains no parseable faces.
227    pub fn register_font_shared_as(
228        &mut self,
229        data: crate::font::SharedFontData,
230        family: &str,
231        weight: u16,
232        italic: bool,
233    ) -> FontFaceId {
234        let ids = self
235            .font_registry
236            .register_font_shared_as(data, family, weight, italic);
237        ids.into_iter()
238            .next()
239            .expect("font data contained no faces")
240    }
241
242    /// Set which face to use as the document default, plus its base
243    /// size in logical pixels. This is the fallback font when a
244    /// fragment's `TextFormat` doesn't specify a family or when the
245    /// requested family isn't found.
246    pub fn set_default_font(&mut self, face: FontFaceId, size_px: f32) {
247        self.font_registry.set_default_font(face, size_px);
248    }
249
250    /// Set the language, as a BCP 47 tag (`"ja"`, `"zh-TW"`), that Chinese
251    /// characters a fallback font draws are drawn for when their text does
252    /// not say: a host passes its UI locale. The same character is drawn
253    /// differently in Japanese, Simplified Chinese, Traditional Chinese and
254    /// Korean, so glyph fallback picks a face for one of them. The language
255    /// of the character's block, then the kana or hangul nearest to it in its
256    /// paragraph, win over this one; with none of the three, Simplified
257    /// Chinese. A tag that names no CJK language, or `None`, sets none.
258    ///
259    /// A change marks every flow laid out against this service as stale, as
260    /// a scale factor change does: [`scale_generation`](Self::scale_generation)
261    /// moves, so [`DocumentFlow::layout_dirty_for_scale`] answers true until
262    /// the flow is laid out again. Setting the language it already has
263    /// changes nothing.
264    ///
265    /// [`DocumentFlow::layout_dirty_for_scale`]: crate::DocumentFlow::layout_dirty_for_scale
266    pub fn set_default_language(&mut self, language: Option<&str>) {
267        if self.font_registry.set_default_language(language) {
268            // Shaped runs chose their fallback faces by the old language.
269            self.scale_generation = self.scale_generation.wrapping_add(1);
270        }
271    }
272
273    /// Set how glyphs are fitted to the pixel grid (see [`GlyphRendering`]).
274    ///
275    /// [`GlyphRendering::Crisp`] changes the advances text is laid out with,
276    /// so a change marks every flow laid out against this service as stale,
277    /// as a scale factor change does: [`scale_generation`](Self::scale_generation)
278    /// moves, so [`DocumentFlow::layout_dirty_for_scale`] answers true until
279    /// the flow is laid out again. Setting the mode it already has changes
280    /// nothing. Glyphs already in the atlas stay valid: the crisp ones are
281    /// cached under keys of their own.
282    ///
283    /// [`DocumentFlow::layout_dirty_for_scale`]: crate::DocumentFlow::layout_dirty_for_scale
284    pub fn set_glyph_rendering(&mut self, rendering: GlyphRendering) {
285        if self.font_registry.set_glyph_rendering(rendering) {
286            self.scale_generation = self.scale_generation.wrapping_add(1);
287        }
288    }
289
290    /// How glyphs are fitted to the pixel grid (default
291    /// [`GlyphRendering::Natural`]).
292    pub fn glyph_rendering(&self) -> GlyphRendering {
293        self.font_registry.glyph_rendering()
294    }
295
296    /// Map a generic family name (e.g. `"serif"`, `"monospace"`) to a
297    /// concrete registered family. When text-document emits a fragment
298    /// whose `font_family` matches a generic, the font resolver looks
299    /// it up through this table before querying fontdb.
300    pub fn set_generic_family(&mut self, generic: &str, family: &str) {
301        self.font_registry.set_generic_family(generic, family);
302    }
303
304    /// Look up the family name of a registered face by id.
305    pub fn font_family_name(&self, face_id: FontFaceId) -> Option<String> {
306        self.font_registry.font_family_name(face_id)
307    }
308
309    /// Borrow the font registry directly — needed by callers that
310    /// want to inspect or extend it beyond the helpers exposed here.
311    pub fn font_registry(&self) -> &FontRegistry {
312        &self.font_registry
313    }
314
315    // ── Font enumeration (font picker) ──────────────────────────
316
317    /// Enumerate every installed font family, deduplicated and sorted.
318    ///
319    /// Cheap (fontdb metadata only — no font bytes loaded). Collapses
320    /// weight/style faces into one entry per family, with `monospaced`
321    /// true when any face of the family is monospaced. The item source for
322    /// a font picker.
323    pub fn families(&self) -> Vec<crate::font::FontFamilyInfo> {
324        self.font_registry.families()
325    }
326
327    /// Enumerate installed font family names, deduplicated and sorted — the
328    /// simple projection of [`families`](Self::families).
329    pub fn family_names(&self) -> Vec<String> {
330        self.font_registry.family_names()
331    }
332
333    /// True if any face of the named family is monospaced (fontdb metadata,
334    /// no bytes loaded). Case-insensitive on the family name.
335    pub fn family_is_monospaced(&self, family: &str) -> bool {
336        self.font_registry.family_is_monospaced(family)
337    }
338
339    /// Build a `Send` snapshot of every family's face byte-sources, to be
340    /// moved to a background thread and turned into a writing-system
341    /// coverage map (see [`WritingSystemIndexBuilder`]).
342    ///
343    /// Cheap on the calling thread; the expensive per-face OS/2 parsing runs
344    /// in [`WritingSystemIndexBuilder::build`] off-thread.
345    ///
346    /// [`WritingSystemIndexBuilder`]: crate::font::WritingSystemIndexBuilder
347    /// [`WritingSystemIndexBuilder::build`]: crate::font::WritingSystemIndexBuilder::build
348    pub fn writing_system_index_builder(&self) -> crate::font::WritingSystemIndexBuilder {
349        self.font_registry.writing_system_index_builder()
350    }
351
352    // ── Font metrics ────────────────────────────────────────────
353
354    /// Line height (in logical pixels) for the registry's default
355    /// font + size, computed as `ascent + descent + leading`.
356    ///
357    /// Useful for callers that need to size a widget against the
358    /// intrinsic line height *before* any content has been laid out
359    /// (an empty editor that wants to report a `min_lines`-tall
360    /// intrinsic size, for example). Returns `0.0` when no default
361    /// font is registered or the face cannot be opened.
362    ///
363    /// Does not apply any per-block `line_height_multiplier` —
364    /// multipliers live on `BlockFormat`, not on the font, and have
365    /// no meaning when there's no block to multiply against. Use
366    /// [`measure_line_height`](Self::measure_line_height) when you
367    /// already have a [`TextFormat`].
368    pub fn default_line_height(&self) -> f32 {
369        self.measure_line_height(&TextFormat::default())
370    }
371
372    /// Line height (in logical pixels) for an explicit
373    /// [`TextFormat`], computed as `ascent + descent + leading` of
374    /// the resolved font at the resolved size. Fields left as `None`
375    /// fall back to the registry's defaults — same resolution path
376    /// as live inline runs (see `font::resolve::resolve_font`).
377    ///
378    /// Returns `0.0` when the format cannot be resolved (no default
379    /// font registered, requested family missing and no fallback,
380    /// face fails to open).
381    pub fn measure_line_height(&self, format: &TextFormat) -> f32 {
382        let font_point_size = format.font_size.map(|s| s as u32);
383        let resolved = match resolve_font(
384            &self.font_registry,
385            format.font_family.as_deref(),
386            format.font_weight,
387            format.font_bold,
388            format.font_italic,
389            font_point_size,
390            self.scale_factor,
391            1.0, // explicit format size is already scaled by the caller
392        ) {
393            Some(r) => r,
394            None => return 0.0,
395        };
396        match font_metrics_px(&self.font_registry, &resolved) {
397            Some(m) => m.ascent + m.descent + m.leading,
398            None => 0.0,
399        }
400    }
401
402    // ── HiDPI scale factor ──────────────────────────────────────
403
404    /// Set the device pixel ratio for HiDPI rasterization.
405    ///
406    /// Layout stays in logical pixels; glyphs are shaped and
407    /// rasterized at `size_px * scale_factor` so text is crisp on
408    /// HiDPI displays. Orthogonal to [`DocumentFlow::set_zoom`],
409    /// which is a post-layout display transform.
410    ///
411    /// Changing this value invalidates the glyph cache and the
412    /// atlas (both are cleared here) and marks every
413    /// [`DocumentFlow`] that was laid out against this service as
414    /// stale via the `scale_generation` counter. The caller must
415    /// then re-run `layout_full` / `layout_blocks` on every flow
416    /// before the next render — existing shaped advances depended
417    /// on the old ppem rounding.
418    ///
419    /// Clamped to `0.25..=8.0`. Default is `1.0`.
420    ///
421    /// [`DocumentFlow`]: crate::DocumentFlow
422    /// [`DocumentFlow::set_zoom`]: crate::DocumentFlow::set_zoom
423    pub fn set_scale_factor(&mut self, scale_factor: f32) {
424        let sf = scale_factor.clamp(0.25, 8.0);
425        if (self.scale_factor - sf).abs() <= f32::EPSILON {
426            return;
427        }
428        self.scale_factor = sf;
429        // Glyph raster cells were produced at the old physical size
430        // and would be wrong at the new one. Drop the cache outright.
431        self.glyph_cache.entries.clear();
432        // The bucketed allocator still holds the rectangles for those
433        // evicted glyphs; start from a fresh allocator so the space
434        // is actually reclaimed rather than fragmented.
435        self.atlas = GlyphAtlas::new();
436        // Bump the generation so per-widget flows can detect the
437        // invalidation and re-run their layouts.
438        self.scale_generation = self.scale_generation.wrapping_add(1);
439        // Wholesale atlas reset — anything keyed on the old eviction
440        // epoch must refuse to reuse cached atlas coordinates.
441        self.eviction_epoch = self.eviction_epoch.wrapping_add(1);
442    }
443
444    /// The current scale factor (default `1.0`).
445    pub fn scale_factor(&self) -> f32 {
446        self.scale_factor
447    }
448
449    /// Monotonic counter bumped by every successful
450    /// [`set_scale_factor`](Self::set_scale_factor) call, and by every
451    /// [`set_default_language`](Self::set_default_language) that changes the
452    /// language.
453    ///
454    /// `DocumentFlow` snapshots this during layout so the framework
455    /// can ask whether a flow needs to be re-laid out after a HiDPI
456    /// change without having to track the transition itself.
457    pub fn scale_generation(&self) -> u64 {
458        self.scale_generation
459    }
460
461    /// Monotonic counter bumped every time the atlas drops entries —
462    /// LRU eviction triggered by [`atlas_snapshot`](Self::atlas_snapshot),
463    /// LRU eviction at the start of every full
464    /// [`render`](crate::DocumentFlow::render) (inside
465    /// `build_render_frame`), or wholesale reset by
466    /// [`set_scale_factor`](Self::set_scale_factor).
467    ///
468    /// This is the single source of truth for "retained glyph quads may
469    /// be stale": frameworks should compare it against a last-seen value
470    /// once per frame and invalidate every retained paint cache when it
471    /// moves, regardless of which path moved it.
472    ///
473    /// Per-widget [`crate::DocumentFlow`]s stamp this value on every full
474    /// [`render`](crate::DocumentFlow::render) and refuse to reuse
475    /// their cached glyph quads on subsequent
476    /// [`render_cursor_only`](crate::DocumentFlow::render_cursor_only)
477    /// or [`render_block_only`](crate::DocumentFlow::render_block_only)
478    /// calls when the epoch has advanced — at that point any baked-in
479    /// atlas pixel coordinates in those cached quads may reference
480    /// slots now owned by unrelated glyphs.
481    pub fn eviction_epoch(&self) -> u64 {
482        self.eviction_epoch
483    }
484
485    // ── Atlas ───────────────────────────────────────────────────
486
487    /// Read the glyph atlas state without triggering a render.
488    ///
489    /// Optionally advances the cache generation and runs eviction.
490    /// Returns an [`AtlasSnapshot`] the caller can pattern-match
491    /// by field. The atlas's internal dirty flag is cleared here,
492    /// so the caller must either upload `pixels` during the
493    /// returned borrow or accept a one-frame delay.
494    ///
495    /// When `snapshot.glyphs_evicted` is true, callers that cache
496    /// glyph positions (e.g. paint caches) must invalidate —
497    /// evicted atlas slots may be reused by subsequent allocations
498    /// and old UVs would now point to the wrong glyph.
499    ///
500    /// Only advance the generation on frames where actual text
501    /// work happened; skipping eviction on idle frames prevents
502    /// aging out glyphs that are still visible but not re-measured
503    /// this tick.
504    pub fn atlas_snapshot(&mut self, advance_generation: bool) -> AtlasSnapshot<'_> {
505        let mut glyphs_evicted = false;
506        if advance_generation {
507            self.glyph_cache.advance_generation();
508            let evicted = self.glyph_cache.evict_unused();
509            glyphs_evicted = !evicted.is_empty();
510            if glyphs_evicted {
511                self.eviction_epoch = self.eviction_epoch.wrapping_add(1);
512            }
513            for glyph in evicted {
514                self.atlas.deallocate(glyph.alloc_id);
515                #[cfg(debug_assertions)]
516                self.atlas.debug_poison_rect(
517                    glyph.atlas_x,
518                    glyph.atlas_y,
519                    glyph.width,
520                    glyph.height,
521                );
522            }
523        }
524
525        let dirty = self.atlas.dirty;
526        let width = self.atlas.width;
527        let height = self.atlas.height;
528        if dirty {
529            self.atlas.dirty = false;
530        }
531        AtlasSnapshot {
532            dirty,
533            width,
534            height,
535            pixels: &self.atlas.pixels[..],
536            glyphs_evicted,
537        }
538    }
539
540    /// Mark the given glyph cache keys as used in the current
541    /// generation, preventing them from being evicted. Use this when
542    /// glyph quads are cached externally (e.g. per-widget paint
543    /// caches) and the normal `rasterize_glyph_quad` → `get()` path
544    /// is skipped.
545    pub fn touch_glyphs(&mut self, keys: &[crate::atlas::cache::GlyphCacheKey]) {
546        self.glyph_cache.touch(keys);
547    }
548
549    /// Current atlas rectangle (`[x, y, w, h]`, atlas pixel coordinates)
550    /// for a cached glyph, without refreshing its LRU timestamp.
551    ///
552    /// Returns `None` when the glyph is not (or no longer) resident.
553    /// Intended for debug-build validation of externally retained glyph
554    /// quads: a quad whose baked rect no longer matches the live rect is
555    /// sampling pixels that belong to another glyph.
556    pub fn peek_glyph_rect(&self, key: &crate::atlas::cache::GlyphCacheKey) -> Option<[u32; 4]> {
557        self.glyph_cache
558            .peek(key)
559            .map(|g| [g.atlas_x, g.atlas_y, g.width, g.height])
560    }
561
562    /// Test hook: overwrite the atlas rectangle recorded for a cached
563    /// glyph. Lets corruption-detector tests simulate a glyph whose atlas
564    /// slot moved underneath a retained quad. Returns `false` when the
565    /// key is not resident.
566    #[doc(hidden)]
567    pub fn debug_set_glyph_rect(
568        &mut self,
569        key: &crate::atlas::cache::GlyphCacheKey,
570        rect: [u32; 4],
571    ) -> bool {
572        match self.glyph_cache.entries.get_mut(key) {
573            Some(glyph) => {
574                glyph.atlas_x = rect[0];
575                glyph.atlas_y = rect[1];
576                glyph.width = rect[2];
577                glyph.height = rect[3];
578                true
579            }
580            None => false,
581        }
582    }
583
584    /// True if the atlas has pending pixel changes since the last
585    /// upload. The atlas is marked clean after every `render()` that
586    /// copies pixels into its `RenderFrame`; this accessor exposes
587    /// the flag for framework paint-cache invalidation decisions.
588    pub fn atlas_dirty(&self) -> bool {
589        self.atlas.dirty
590    }
591
592    /// Current atlas texture width in pixels.
593    pub fn atlas_width(&self) -> u32 {
594        self.atlas.width
595    }
596
597    /// Current atlas texture height in pixels.
598    pub fn atlas_height(&self) -> u32 {
599        self.atlas.height
600    }
601
602    /// Raw atlas pixel buffer (RGBA8).
603    pub fn atlas_pixels(&self) -> &[u8] {
604        &self.atlas.pixels
605    }
606
607    /// Mark the atlas clean after the caller has uploaded its
608    /// contents to the GPU. Paired with `atlas_dirty` + `atlas_pixels`
609    /// for framework adapters that upload directly from the service
610    /// instead of consuming `RenderFrame::atlas_pixels`.
611    pub fn mark_atlas_clean(&mut self) {
612        self.atlas.dirty = false;
613    }
614}
615
616impl Default for TextFontService {
617    fn default() -> Self {
618        Self::new()
619    }
620}