Rendering parity (software ↔ GLES). The software backend now rounds glyph pen positions and image destinations to the nearest integer pixel, matching what the GLES backend already did; previously it truncated, so text and 1:1 images could land up to half a pixel off between the two backends and the bilinear sample read ~1 px softer than the source. Gradients and shadows are deliberately left unimplemented on the software backend, and the GLES multi-rect `glScissor` clip is left coarse on purpose: making it exact would need stencil bits the EGL config does not carry, or routing the partial-redraw path through the offscreen clip layer, which would break its `fill` / `clear_rects_transparent` scissor semantics. Adds software-backend pixel tests covering the snapping. Font resolution unification. The system-font candidate chain, `find_font_opt` and `load_default_font_bytes` lived in two copies (`render/helpers` and `gles_render/helpers`) that had already diverged — one resolved through `find_font_opt`, the other inlined the candidate loop — and now live once in `system_fonts`. The two per-backend `OnceLock` default-font caches and `primary_handle` collapse into a single `system_fonts::default_handle`. Module docs and the `font_registry` caller are updated accordingly. Shared image validation and rect inflation. `draw_image_data`'s dimension check and its one-line warning were byte-duplicated across both backends and are now `render::helpers::validate_rgba_dims`. The six manual symmetric `Rect`-inflate literals in the GLES primitives reuse the existing `Rect::expand`. FrameState and DrawCtx de-duplication. The eleven `SurfaceState` fields the draw pass owns and threads through `DrawCtx` — `widget_rects`, the cursor / selection maps, the scroll state, `accessible_extras`, `prev_focused` / `prev_hovered` / `prev_pressed` — move into a `FrameState` sub-struct. The per-frame `build_draw_ctx` / `commit_draw_ctx` helpers can then borrow `&mut ss.frame`, disjoint from `ss.canvas` and `ss.pool`, so the four frame paths (software / GLES × full / partial) replace their duplicated `DrawCtx` construction and write-back with a single helper call each. A whole-`SurfaceState` borrow could not express this (partial borrows do not cross function boundaries), which is why the helpers take the sub-struct. `content_dirty` stays on `SurfaceState` — it is an invalidation flag, not frame state — and is reset at the call site. rich_text tests. Adds the previously-missing `tests.rs` for the `RichText` widget: one hit rect per visual line a link spans (the widget's core invariant), the single-line and no-link cases, preferred-size growth with hard line breaks, and `map_msg` range preservation — all headless against a software `Canvas`, with line counts forced by `\n` so they do not depend on any system font's measured width. Documentation. Fills the rustdoc gaps on the embedder-facing surface: `core::UiSurface` accessors, the `egl_context` public API, the `GlesCanvas` methods, `theme::typography` and `theme::error`, and the `RichText` / `Text` builders; adds a crate-level "Rendering backends" overview. `CHANGELOG.md` is added (0.2.0 / 0.1.0), and `docs/widgets.md` / `docs/cookbook.md` gain `rich_text`, `external`, and the CPU-draw / path-clip / externally-laid-out-tree recipes. `debian/changelog` gets the 0.2.0-1 entry. Private intra-doc links to `system_fonts` are demoted to code spans so `cargo doc` is warning-free. Packaging. The `libltk-dev` registry crate shipped a `Cargo.toml` declaring the `lookup` bench while the `Makefile` install copied only `src/`, so Cargo refused to parse the manifest over a missing `benches/lookup.rs`; the install now ships `benches/` as well (the file alone satisfies the parse — criterion is a dev-dependency and is not resolved when the crate is consumed as a library). `Cargo.toml` is bumped to 0.2.0 to match the package version and the `ltk-0.2.0` registry directory.
238 lines
9.9 KiB
Rust
238 lines
9.9 KiB
Rust
// SPDX-License-Identifier: LGPL-2.1-only
|
|
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
|
|
|
|
//! Process-wide font resolution for both backends: the primary UI font
|
|
//! ([`default_handle`] / [`primary_handle`], loaded once from the
|
|
//! [`SYSTEM_FONT_CANDIDATES`] chain) and lazy per-glyph fallback.
|
|
//!
|
|
//! The default font ([`crate::theme::fallback::FALLBACK_FONT`], Sora)
|
|
//! covers Latin and a portion of extended Latin; everything outside
|
|
//! that band — Cyrillic, Devanagari, Arabic, Hebrew, Thai, the CJK
|
|
//! ideographic block — relies on a chain of system Noto fonts loaded
|
|
//! on demand: a fallback file is read off disk the first time some
|
|
//! glyph asks for it and the resulting `Arc<Font>` is cached
|
|
//! process-wide.
|
|
//!
|
|
//! Each `(path, face)` entry in [`FALLBACK_FONT_CANDIDATES`] gets its
|
|
//! own `OnceLock<Option<Arc<Font>>>` slot. `Some(font)` means the
|
|
//! file was read and parsed successfully; `None` means it's missing
|
|
//! or unparseable, locked in for the rest of the process so we don't
|
|
//! re-`stat` the same path on every glyph miss. The `OnceLock`
|
|
//! handles concurrent first-loads correctly: at most one thread runs
|
|
//! the closure for a given slot, the rest wait for the result.
|
|
//!
|
|
//! Renderers (`SoftwareCanvas` and `GlesCanvas`) consult this module
|
|
//! through [`lookup`] in their `font_for_char` paths.
|
|
|
|
use std::sync::{ Arc, OnceLock };
|
|
|
|
use fontdue::{ Font, FontSettings };
|
|
|
|
/// Bytes-aware font handle. The `font` is what fontdue rasterises
|
|
/// against; `bytes` is the raw OpenType / TrueType buffer that
|
|
/// rustybuzz (HarfBuzz) requires for shaping. They are owned
|
|
/// separately because fontdue does not expose its internal byte
|
|
/// buffer — we keep both alive in lockstep instead.
|
|
///
|
|
/// `face` is the TTC sub-face index (0 for single-face files, the
|
|
/// face index for collections like Noto Sans CJK).
|
|
#[ derive( Clone ) ]
|
|
pub struct FontHandle
|
|
{
|
|
pub font: Arc<Font>,
|
|
pub bytes: Arc<Vec<u8>>,
|
|
pub face: u32,
|
|
}
|
|
|
|
/// Per-script fallback font path with the TrueType-collection face
|
|
/// index fontdue should load (most files are single-face → 0; CJK
|
|
/// `.ttc` archives carry many faces, see the SC face on the canonical
|
|
/// Adobe-built `NotoSansCJK-Regular.ttc`).
|
|
struct FallbackFontSpec
|
|
{
|
|
path: &'static str,
|
|
face: u32,
|
|
}
|
|
|
|
/// Ordered fallback chain consulted on a glyph miss. Order matters:
|
|
/// the first slot whose font owns a non-zero glyph index for the
|
|
/// codepoint wins, so the broadest families come first (Noto Sans
|
|
/// covers Cyrillic, Greek, extended Latin) and the script-specific
|
|
/// + CJK packs trail. DejaVu is the last resort — most distros carry
|
|
/// it under one path or another.
|
|
const FALLBACK_FONT_CANDIDATES: &[ FallbackFontSpec ] =
|
|
&[
|
|
// Noto Sans — Cyrillic, Greek, extended Latin.
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", face: 0 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/noto/NotoSans-Regular.ttf", face: 0 },
|
|
|
|
// Devanagari (Hindi).
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/noto/NotoSansDevanagari-Regular.ttf", face: 0 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/noto/NotoSansDevanagari-Regular.ttf", face: 0 },
|
|
|
|
// Arabic, Hebrew, Thai — common scripts cheap to keep.
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf", face: 0 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", face: 0 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/noto/NotoSansThai-Regular.ttf", face: 0 },
|
|
|
|
// CJK packs ship as `.ttc`. The collection layout on the canonical
|
|
// Adobe-built `NotoSansCJK-Regular.ttc` is 0=JP, 1=KR, 2=SC, 3=TC,
|
|
// 4=HK; we want CJK shared ideographs available in any locale, so
|
|
// any of the faces is fine — pick SC (face 2) as the broadest
|
|
// baseline. ~30 MB on disk; under the lazy loader this only fires
|
|
// when a user-visible string actually contains a CJK codepoint.
|
|
FallbackFontSpec { path: "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", face: 2 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/opentype/noto-cjk/NotoSansCJK-Regular.ttc", face: 2 },
|
|
FallbackFontSpec { path: "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", face: 2 },
|
|
|
|
// Last resort — DejaVu has broad-but-shallow coverage of most
|
|
// scripts and ships almost everywhere.
|
|
FallbackFontSpec { path: "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", face: 0 },
|
|
];
|
|
|
|
/// Per-slot lazy state. `Vec` length matches
|
|
/// [`FALLBACK_FONT_CANDIDATES`]; each `OnceLock` resolves
|
|
/// independently so the act of looking up a Devanagari codepoint
|
|
/// doesn't drag the CJK pack into memory. `None` inside a resolved
|
|
/// slot means the file was missing or fontdue rejected it — a sticky
|
|
/// negative result so subsequent misses skip the slot in O(1).
|
|
fn slots() -> &'static [ OnceLock<Option<FontHandle>> ]
|
|
{
|
|
static SLOTS: OnceLock<Vec<OnceLock<Option<FontHandle>>>> = OnceLock::new();
|
|
SLOTS.get_or_init( ||
|
|
{
|
|
( 0..FALLBACK_FONT_CANDIDATES.len() )
|
|
.map( |_| OnceLock::new() )
|
|
.collect()
|
|
} )
|
|
}
|
|
|
|
/// Try to load and parse the fallback font at slot `idx`. Each
|
|
/// `OnceLock` wraps `Option<FontHandle>` so a missing or malformed
|
|
/// file is recorded as `None` and never re-attempted. The raw bytes
|
|
/// are preserved inside the handle so the same `Arc<Vec<u8>>` can be
|
|
/// handed to rustybuzz for shaping without re-reading the file.
|
|
fn slot_handle( idx: usize ) -> Option<FontHandle>
|
|
{
|
|
let slot = &slots()[ idx ];
|
|
slot.get_or_init( ||
|
|
{
|
|
let spec = &FALLBACK_FONT_CANDIDATES[ idx ];
|
|
let bytes = std::fs::read( spec.path ).ok()?;
|
|
let opts = FontSettings { collection_index: spec.face, ..FontSettings::default() };
|
|
let font = Font::from_bytes( bytes.as_slice(), opts ).ok()?;
|
|
Some( FontHandle
|
|
{
|
|
font: Arc::new( font ),
|
|
bytes: Arc::new( bytes ),
|
|
face: spec.face,
|
|
} )
|
|
} )
|
|
.clone()
|
|
}
|
|
|
|
/// Find the first fallback font that has a non-zero glyph index for
|
|
/// `ch`, loading it from disk on the first hit and caching the
|
|
/// `Arc<Font>` for the rest of the process. Returns `None` if no
|
|
/// installed fallback covers the codepoint — the caller then paints
|
|
/// the primary font's `.notdef` rather than dropping the glyph.
|
|
///
|
|
/// Side effect: walking the chain may load and cache a slot even if
|
|
/// it doesn't end up covering `ch` (`lookup_glyph_index` reads the
|
|
/// `cmap` table, which requires the font to be parsed). That's
|
|
/// acceptable — the slot is cached on the first encounter regardless,
|
|
/// and most coverage gaps in early slots are the small Noto Sans
|
|
/// scripts (Devanagari, Arabic, …) whose total weight is a fraction
|
|
/// of the CJK pack everyone was paying for unconditionally.
|
|
pub fn lookup( ch: char ) -> Option<Arc<Font>>
|
|
{
|
|
lookup_handle( ch ).map( |h| h.font )
|
|
}
|
|
|
|
/// System-font search chain for the primary UI font, ordered by preference.
|
|
/// Shared by [`find_font_opt`] and [`load_default_font_bytes`].
|
|
const SYSTEM_FONT_CANDIDATES: &[&str] =
|
|
&[
|
|
// Debian `fonts-sora` — the canonical path `ltk-theme-default`
|
|
// depends on. Listed first so Sora wins as the default font
|
|
// whenever the package is installed.
|
|
"/usr/share/fonts/opentype/sora/Sora-Regular.otf",
|
|
"/usr/share/fonts/truetype/sora/Sora-Regular.ttf",
|
|
"/usr/share/fonts/sora/Sora-Regular.ttf",
|
|
"/usr/share/fonts/TTF/Sora-Regular.ttf",
|
|
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
|
|
"/usr/share/fonts/liberation/LiberationSans-Regular.ttf",
|
|
"/usr/share/fonts/truetype/freefont/FreeSans.ttf",
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
|
"/usr/share/fonts/TTF/DejaVuSans.ttf",
|
|
];
|
|
|
|
/// Resolve the first system font available from [`SYSTEM_FONT_CANDIDATES`], or
|
|
/// `None` if none exist. Used by the font registry and by tests that skip
|
|
/// gracefully on images without the usual fonts installed.
|
|
pub ( crate ) fn find_font_opt() -> Option<String>
|
|
{
|
|
SYSTEM_FONT_CANDIDATES.iter()
|
|
.find( |p| std::path::Path::new( p ).exists() )
|
|
.copied()
|
|
.map( str::to_string )
|
|
}
|
|
|
|
/// Load the bytes of a default system font. Tries the candidate chain via
|
|
/// [`find_font_opt`]; falls back to the embedded
|
|
/// [`crate::theme::fallback::FALLBACK_FONT`] (Sora Regular, ~50 KB, OFL 1.1)
|
|
/// when nothing matches or the file cannot be read. Always returns usable bytes
|
|
/// so canvas construction never panics on a system without the expected fonts.
|
|
pub ( crate ) fn load_default_font_bytes() -> Vec<u8>
|
|
{
|
|
if let Some( path ) = find_font_opt()
|
|
{
|
|
if let Ok( bytes ) = std::fs::read( &path )
|
|
{
|
|
return bytes;
|
|
}
|
|
}
|
|
crate::theme::fallback::FALLBACK_FONT.to_vec()
|
|
}
|
|
|
|
/// The process-wide primary UI font handle — the single default every canvas
|
|
/// loads. Cached so a layer shell bringing up several surfaces parses the small
|
|
/// Sora face once rather than per surface. The per-glyph fallback chain (Noto
|
|
/// Sans / CJK / Devanagari / …) is loaded lazily through [`lookup`], not here.
|
|
pub ( crate ) fn default_handle() -> FontHandle
|
|
{
|
|
static PRIMARY: OnceLock<FontHandle> = OnceLock::new();
|
|
PRIMARY.get_or_init( ||
|
|
{
|
|
let bytes = load_default_font_bytes();
|
|
let font = Font::from_bytes( bytes.as_slice(), FontSettings::default() ).expect( "primary font parses" );
|
|
FontHandle { font: Arc::new( font ), bytes: Arc::new( bytes ), face: 0 }
|
|
} ).clone()
|
|
}
|
|
|
|
/// The process-wide primary UI font — the same default a canvas loads — for
|
|
/// standalone text measurement (e.g. an embedded measure pass with no live
|
|
/// canvas). Falls back to the bundled font when no system font is found.
|
|
pub fn primary_handle() -> FontHandle
|
|
{
|
|
default_handle()
|
|
}
|
|
|
|
/// Bytes-aware variant of [`lookup`]. Returns the full
|
|
/// [`FontHandle`] (fontdue handle + raw bytes + face index) so
|
|
/// callers that need to invoke a HarfBuzz-style shaper can do so
|
|
/// without re-reading the font file.
|
|
pub fn lookup_handle( ch: char ) -> Option<FontHandle>
|
|
{
|
|
for idx in 0..FALLBACK_FONT_CANDIDATES.len()
|
|
{
|
|
let Some( handle ) = slot_handle( idx ) else { continue };
|
|
if handle.font.lookup_glyph_index( ch ) != 0
|
|
{
|
|
return Some( handle );
|
|
}
|
|
}
|
|
None
|
|
}
|