Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

33.0 KB
Raw Blame
use std::collections::BTreeMap;
use std::sync::Arc;

use emath::{vec2, Vec2};

use crate::{
    mutex::{Mutex, RwLock},
    text::FontTweak,
    TextureAtlas,
};

// ----------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct UvRect {
    /// X/Y offset for nice rendering (unit: points).
    pub offset: Vec2,

    /// Screen size (in points) of this glyph.
    /// Note that the height is different from the font height.
    pub size: Vec2,

    /// Top left corner UV in texture.
    pub min: [u16; 2],

    /// Bottom right corner (exclusive).
    pub max: [u16; 2],

    /// RustCord: draw with plain (grayscale) antialiasing even when text is
    /// drawn with LCD subpixel antialiasing: icon fonts, which a browser
    /// draws as pictures.
    pub gray: bool,
}

impl UvRect {
    pub fn is_nothing(&self) -> bool {
        self.min == self.max
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlyphInfo {
    /// Used for pair-kerning.
    ///
    /// Doesn't need to be unique.
    /// Use `ab_glyph::GlyphId(0)` if you just want to have an id, and don't care.
    pub(crate) id: ab_glyph::GlyphId,

    /// Unit: points.
    pub advance_width: f32,

    /// Texture coordinates.
    pub uv_rect: UvRect,
}

impl Default for GlyphInfo {
    /// Basically a zero-width space.
    fn default() -> Self {
        Self {
            id: ab_glyph::GlyphId(0),
            advance_width: 0.0,
            uv_rect: Default::default(),
        }
    }
}

// ----------------------------------------------------------------------------

/// RustCord: empty texture columns around a glyph's image in the atlas: on
/// the left two for the layout's shift by a third of a pixel and two for the
/// shader's filter taps, on the right two for the filter.
const MARGIN_LEFT: usize = 4;
const MARGIN_RIGHT: usize = 2;

/// RustCord: one cluster of shaped text (see [`FontImpl::shape_run`]): the
/// characters that make one picture, such as an Arabic letter in the form
/// its neighbours give it, with its marks.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ShapedCluster {
    /// Bytes of the text it stands for.
    pub byte_len: usize,

    /// Unit: points.
    pub advance_width: f32,

    /// The cluster's picture, placed from the pen as a glyph's is.
    pub uv_rect: UvRect,
}

/// A specific font with a size.
/// The interface uses points as the unit for everything.
pub struct FontImpl {
    name: String,
    ab_glyph_font: ab_glyph::FontArc,

    /// Face index in the font file (non-zero within a `.ttc` collection).
    index: u32,

    /// RustCord: see [`crate::text::FontData::only`].
    only: Option<fn(char) -> bool>,

    /// Maximum character height. RustCord: not rounded to whole pixels, so
    /// text is exactly as wide as a browser lays it out.
    scale_in_pixels: f32,

    /// RustCord: GPOS kerning per glyph pair, in font units.
    kern_cache: RwLock<ahash::HashMap<(u16, u16), i16>>,

    /// RustCord: an icon font, drawn without LCD antialiasing (see `UvRect::gray`).
    gray: bool,

    /// RustCord: the font's bytes and pixels per em for its own hinting.
    hinting: Option<(&'static [u8], u32, f32)>,

    /// RustCord: the font's own hinting at this size, if it has any (see
    /// `super::hinted`): glyphs are then drawn from the hinted outlines. Made
    /// on the first glyph drawn, so the many fallback fonts that never draw
    /// one at a size (other scripts, symbols) cost nothing there.
    hinted: std::sync::OnceLock<Option<super::hinted::Hinted>>,

    height_in_points: f32,

    // move each character by this much (hack)
    y_offset_in_points: f32,

    ascent: f32,
    pixels_per_point: f32,
    glyph_info_cache: RwLock<ahash::HashMap<char, GlyphInfo>>, // TODO(emilk): standard Mutex

    /// RustCord: the shaper for this font's `'static` bytes (see
    /// `shape_run`), made on first use.
    shaper: std::sync::OnceLock<Option<rustybuzz::Face<'static>>>,

    /// RustCord: clusters already drawn into the atlas, by their glyphs and
    /// where those sit (in thirds of a pixel across), so a letter form that
    /// comes again reuses its picture.
    shaped_cache: RwLock<ahash::HashMap<Vec<(u16, i32, i32)>, UvRect>>,

    atlas: Arc<Mutex<TextureAtlas>>,
}

impl FontImpl {
    pub fn new(
        atlas: Arc<Mutex<TextureAtlas>>,
        pixels_per_point: f32,
        name: String,
        ab_glyph_font: ab_glyph::FontArc,
        index: u32,
        only: Option<fn(char) -> bool>,
        scale_in_pixels: f32,
        tweak: FontTweak,
        hinting: Option<(&'static [u8], u32, f32)>,
    ) -> Self {
        assert!(scale_in_pixels > 0.0);
        assert!(pixels_per_point > 0.0);

        use ab_glyph::{Font, ScaleFont};
        let scaled = ab_glyph_font.as_scaled(scale_in_pixels);
        let ascent = scaled.ascent() / pixels_per_point;
        let descent = scaled.descent() / pixels_per_point;
        let line_gap = scaled.line_gap() / pixels_per_point;

        // Tweak the scale as the user desired
        let scale_in_pixels = scale_in_pixels * tweak.scale;

        let baseline_offset = {
            let scale_in_points = scale_in_pixels / pixels_per_point;
            scale_in_points * tweak.baseline_offset_factor
        };

        let y_offset_points = {
            let scale_in_points = scale_in_pixels / pixels_per_point;
            scale_in_points * tweak.y_offset_factor
        } + tweak.y_offset;

        // Center scaled glyphs properly:
        let height = ascent + descent;
        let y_offset_points = y_offset_points - (1.0 - tweak.scale) * 0.5 * height;


        // Round to closest pixel:
        let y_offset_in_points = (y_offset_points * pixels_per_point).round() / pixels_per_point;

        let gray = {
            let lower = name.to_ascii_lowercase();
            lower.contains("icons") || lower.contains("segmdl2")
        };

        // (Not for icons: their shapes aren't letters to be fitted to a grid.)
        let hinting = hinting.filter(|_| !gray);

        Self {
            name,
            ab_glyph_font,
            index,
            only,
            scale_in_pixels,
            kern_cache: Default::default(),
            gray,
            hinting,
            hinted: std::sync::OnceLock::new(),
            height_in_points: ascent - descent + line_gap,
            y_offset_in_points,
            ascent: ascent + baseline_offset,
            pixels_per_point,
            glyph_info_cache: Default::default(),
            shaper: std::sync::OnceLock::new(),
            shaped_cache: Default::default(),
            atlas,
        }
    }

    /// Code points that will always be replaced by the replacement character.
    ///
    /// See also [`invisible_char`].
    fn ignore_character(&self, chr: char) -> bool {
        use crate::text::FontDefinitions;

        if self.only.is_some_and(|only| !only(chr)) {
            return true;
        }

        if !FontDefinitions::builtin_font_names().contains(&self.name.as_str()) {
            return false;
        }

        if self.name == "emoji-icon-font" {
            // HACK: https://github.com/emilk/egui/issues/1284 https://github.com/jslegers/emoji-icon-font/issues/18
            // Don't show the wrong fullwidth capital letters:
            if 'S' <= chr && chr <= 'Y' {
                return true;
            }
        }

        matches!(
            chr,
            // Strip out a religious symbol with secondary nefarious interpretation:
            '\u{534d}' | '\u{5350}' |

            // Ignore ubuntu-specific stuff in `Ubuntu-Light.ttf`:
            '\u{E0FF}' | '\u{EFFD}' | '\u{F0FF}' | '\u{F200}'
        )
    }

    /// An un-ordered iterator over all supported characters.
    fn characters(&self) -> impl Iterator<Item = char> + '_ {
        use ab_glyph::Font as _;
        self.ab_glyph_font
            .codepoint_ids()
            .map(|(_, chr)| chr)
            .filter(|&chr| !self.ignore_character(chr))
    }

    /// `\n` will result in `None`
    fn glyph_info(&self, c: char) -> Option<GlyphInfo> {
        {
            if let Some(glyph_info) = self.glyph_info_cache.read().get(&c) {
                return Some(*glyph_info);
            }
        }

        if self.ignore_character(c) {
            return None; // these will result in the replacement character when rendering
        }

        if c == '\t' {
            if let Some(space) = self.glyph_info(' ') {
                let glyph_info = GlyphInfo {
                    advance_width: crate::text::TAB_SIZE as f32 * space.advance_width,
                    ..space
                };
                self.glyph_info_cache.write().insert(c, glyph_info);
                return Some(glyph_info);
            }
        }

        if c == '\u{2009}' {
            // Thin space, often used as thousands deliminator: 1 234 567 890
            // https://www.compart.com/en/unicode/U+2009
            // https://en.wikipedia.org/wiki/Thin_space

            if let Some(space) = self.glyph_info(' ') {
                let em = self.height_in_points; // TODO(emilk): is this right?
                let advance_width = f32::min(em / 6.0, space.advance_width * 0.5);
                let glyph_info = GlyphInfo {
                    advance_width,
                    ..space
                };
                self.glyph_info_cache.write().insert(c, glyph_info);
                return Some(glyph_info);
            }
        }

        if invisible_char(c) {
            let glyph_info = GlyphInfo::default();
            self.glyph_info_cache.write().insert(c, glyph_info);
            return Some(glyph_info);
        }

        // Add new character:
        use ab_glyph::Font as _;
        let glyph_id = self.ab_glyph_font.glyph_id(c);

        if glyph_id.0 == 0 {
            None // unsupported character
        } else {
            let glyph_info = self.allocate_glyph(glyph_id);
            self.glyph_info_cache.write().insert(c, glyph_info);
            Some(glyph_info)
        }
    }

    /// Kerning between two glyphs, in points. RustCord: from the font's GPOS
    /// `kern` feature when it has one (what browsers use; gg sans has no
    /// legacy `kern` table), else ab_glyph's `kern` table lookup.
    #[inline]
    pub fn pair_kerning(
        &self,
        last_glyph_id: ab_glyph::GlyphId,
        glyph_id: ab_glyph::GlyphId,
    ) -> f32 {
        use ab_glyph::{Font as _, ScaleFont};
        let key = (last_glyph_id.0, glyph_id.0);
        let cached = self.kern_cache.read().get(&key).copied();
        let units = cached.unwrap_or_else(|| {
            let units = gpos_kern(self.ab_glyph_font.font_data(), key.0, key.1).unwrap_or(i16::MIN);
            self.kern_cache.write().insert(key, units);
            units
        });
        if units == i16::MIN {
            return self
                .ab_glyph_font
                .as_scaled(self.scale_in_pixels)
                .kern(last_glyph_id, glyph_id)
                / self.pixels_per_point;
        }
        let height = self.ab_glyph_font.height_unscaled();
        units as f32 * self.scale_in_pixels / height / self.pixels_per_point
    }

    /// Height of one row of text in points.
    #[inline(always)]
    pub fn row_height(&self) -> f32 {
        self.height_in_points
    }

    #[inline(always)]
    pub fn pixels_per_point(&self) -> f32 {
        self.pixels_per_point
    }

    /// This is the distance from the top to the baseline.
    ///
    /// Unit: points.
    #[inline(always)]
    pub fn ascent(&self) -> f32 {
        self.ascent
    }

    /// RustCord: a glyph's coverage, three samples per pixel across: from the
    /// font's hinted outline when it has one (see `super::hinted`), else from
    /// the plain outline.
    fn raster_glyph(&self, glyph_id: ab_glyph::GlyphId) -> Option<super::hinted::Raster> {
        use ab_glyph::Font as _;
        self.hinted
            .get_or_init(|| self.hinting.and_then(|(bytes, index, pixels_per_em)| super::hinted::Hinted::new(bytes, index, pixels_per_em)))
            .as_ref()
            .and_then(|h| h.raster(glyph_id.0, 3.0))
            .or_else(|| {
                let glyph = glyph_id.with_scale_and_position(
                    ab_glyph::PxScale {
                        x: self.scale_in_pixels * 3.0,
                        y: self.scale_in_pixels,
                    },
                    ab_glyph::Point { x: 0.0, y: 0.0 },
                );
                let glyph = self.ab_glyph_font.outline_glyph(glyph)?;
                let bb = glyph.px_bounds();
                let (width, height) = (bb.width() as usize, bb.height() as usize);
                let mut coverage = vec![0.0; width * height];
                glyph.draw(|x, y, v| {
                    if let Some(c) = coverage.get_mut(y as usize * width + x as usize) {
                        *c = v;
                    }
                });
                Some(super::hinted::Raster { min_x: bb.min.x as i32, min_y: bb.min.y as i32, width, height, coverage })
            })
    }

    /// RustCord: glyphs are rasterised three times as wide as they are drawn,
    /// one atlas texel per LCD subpixel (the shader filters three texels into
    /// each pixel's red, green and blue, or into one coverage for grayscale).
    /// The image is aligned to whole pixels, with room on the left for the
    /// layout to shift it by a third or two thirds of a pixel (it moves the
    /// glyph's texture coordinates by one or two texels), so one image serves
    /// every subpixel position.
    fn allocate_glyph(&self, glyph_id: ab_glyph::GlyphId) -> GlyphInfo {
        assert!(glyph_id.0 != 0);
        use ab_glyph::{Font as _, ScaleFont};

        let uv_rect = self.raster_glyph(glyph_id).map(|raster| {
            let sub_width = raster.width;
            let glyph_height = raster.height;
            if sub_width == 0 || glyph_height == 0 {
                UvRect::default()
            } else {
                // In subpixels: the ink spans sub_min..sub_max; the filter
                // spreads it by two more on each side, and a shift moves it
                // right by up to two.
                let sub_min = raster.min_x;
                let sub_max = sub_min + sub_width as i32;
                let left = (sub_min - 2).div_euclid(3);
                let right = (sub_max + 4 + 2).div_euclid(3);
                let glyph_width = (right - left) as usize;
                let inset = (sub_min - 3 * left) as usize;

                let glyph_pos = {
                    let atlas = &mut self.atlas.lock();
                    let (pos, image) = atlas.allocate((
                        MARGIN_LEFT + 3 * glyph_width + MARGIN_RIGHT,
                        glyph_height,
                    ));
                    let glyph_pos = (pos.0 + MARGIN_LEFT, pos.1);
                    for y in 0..glyph_height {
                        for x in 0..sub_width {
                            let v = raster.coverage[y * sub_width + x];
                            if 0.0 < v {
                                image.set((glyph_pos.0 + inset + x, glyph_pos.1 + y), v);
                            }
                        }
                    }
                    glyph_pos
                };

                let offset_in_pixels = vec2(left as f32, raster.min_y as f32);
                let offset =
                    offset_in_pixels / self.pixels_per_point + self.y_offset_in_points * Vec2::Y;
                UvRect {
                    offset,
                    size: vec2(glyph_width as f32, glyph_height as f32) / self.pixels_per_point,
                    min: [glyph_pos.0 as u16, glyph_pos.1 as u16],
                    max: [
                        (glyph_pos.0 + 3 * glyph_width) as u16,
                        (glyph_pos.1 + glyph_height) as u16,
                    ],
                    gray: self.gray,
                }
            }
        });
        let uv_rect = uv_rect.unwrap_or_default();

        let advance_width_in_points = self
            .ab_glyph_font
            .as_scaled(self.scale_in_pixels)
            .h_advance(glyph_id)
            / self.pixels_per_point;

        GlyphInfo {
            id: glyph_id,
            advance_width: advance_width_in_points,
            uv_rect,
        }
    }

    /// RustCord: does this font draw `c`? Like [`Self::glyph_info`] without
    /// putting anything in the atlas.
    pub(crate) fn covers(&self, c: char) -> bool {
        use ab_glyph::Font as _;
        !self.ignore_character(c) && (invisible_char(c) || self.ab_glyph_font.glyph_id(c).0 != 0)
    }

    /// RustCord: shapes a run of text the way HarfBuzz does (its letters take
    /// the forms their neighbours call for, marks go on their letters) and
    /// draws each cluster as one picture. The clusters come in the text's
    /// order, whichever way the script runs; `None` if the font can't be
    /// read for shaping.
    pub(crate) fn shape_run(&self, text: &str) -> Option<Vec<ShapedCluster>> {
        use ab_glyph::Font as _;
        let shaper = self.shaper.get_or_init(|| self.hinting.and_then(|(bytes, index, _)| rustybuzz::Face::from_slice(bytes, index)));
        match shaper {
            Some(face) => Some(self.shape_with(face, text)),
            // A font whose bytes aren't `'static` is read for each run.
            None => rustybuzz::Face::from_slice(self.ab_glyph_font.font_data(), self.index).map(|face| self.shape_with(&face, text)),
        }
    }

    fn shape_with(&self, face: &rustybuzz::Face<'_>, text: &str) -> Vec<ShapedCluster> {
        use ab_glyph::Font as _;

        let mut buffer = rustybuzz::UnicodeBuffer::new();
        buffer.push_str(text);
        buffer.guess_segment_properties();
        let shaped = rustybuzz::shape(face, &[], buffer);

        // HarfBuzz works in font units; ab_glyph's scale is the font's
        // unscaled height in pixels, so divide by that rather than the em.
        let units_to_px = self.scale_in_pixels / self.ab_glyph_font.height_unscaled();

        /// A cluster as it comes out: glyphs (id, x from the cluster's left
        /// edge, y down from the baseline, in pixels) left to right.
        struct Cluster {
            start: usize,
            left: f32,
            right: f32,
            glyphs: Vec<(u16, f32, f32)>,
        }
        let mut clusters: Vec<Cluster> = Vec::new();
        let mut pen = 0.0_f32;
        for (info, position) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
            let start = info.cluster as usize;
            if clusters.last().map_or(true, |c| c.start != start) {
                clusters.push(Cluster { start, left: pen, right: pen, glyphs: Vec::new() });
            }
            let cluster = clusters.last_mut().unwrap();
            let x = pen + position.x_offset as f32 * units_to_px - cluster.left;
            // HarfBuzz counts y up, the screen down.
            let y = -(position.y_offset as f32) * units_to_px;
            cluster.glyphs.push((info.glyph_id as u16, x, y));
            pen += position.x_advance as f32 * units_to_px;
            cluster.right = pen;
        }
        // Right-to-left text comes out right to left: put it in text order.
        clusters.sort_by_key(|c| c.start);

        let mut out = Vec::with_capacity(clusters.len());
        let mut covered = 0;
        for (i, cluster) in clusters.iter().enumerate() {
            let end = clusters.get(i + 1).map_or(text.len(), |next| next.start);
            if covered < cluster.start {
                // Characters the shaper dropped keep their place, at no width.
                out.push(ShapedCluster { byte_len: cluster.start - covered, advance_width: 0.0, uv_rect: UvRect::default() });
            }
            out.push(ShapedCluster {
                byte_len: end - cluster.start,
                advance_width: (cluster.right - cluster.left) / self.pixels_per_point,
                uv_rect: self.allocate_cluster(&cluster.glyphs),
            });
            covered = end;
        }
        if covered < text.len() {
            out.push(ShapedCluster { byte_len: text.len() - covered, advance_width: 0.0, uv_rect: UvRect::default() });
        }
        out
    }

    /// RustCord: draws a cluster's glyphs, each where the shaper put it, into
    /// one atlas image (laid out as `allocate_glyph`'s, so the layout shifts
    /// it by thirds of a pixel the same way).
    fn allocate_cluster(&self, glyphs: &[(u16, f32, f32)]) -> UvRect {
        // Where each glyph sits, in thirds of a pixel across and pixels down.
        let placed: Vec<(u16, i32, i32)> =
            glyphs.iter().map(|&(id, x, y)| (id, (x * 3.0).round() as i32, y.round() as i32)).collect();
        if let Some(uv_rect) = self.shaped_cache.read().get(&placed) {
            return *uv_rect;
        }

        let rasters: Vec<(super::hinted::Raster, i32, i32)> = placed
            .iter()
            .filter(|&&(id, _, _)| id != 0)
            .filter_map(|&(id, dx, dy)| self.raster_glyph(ab_glyph::GlyphId(id)).map(|r| (r, dx, dy)))
            .filter(|(r, _, _)| r.width > 0 && r.height > 0)
            .collect();
        let sub_min = rasters.iter().map(|(r, dx, _)| r.min_x + dx).min();
        let sub_max = rasters.iter().map(|(r, dx, _)| r.min_x + dx + r.width as i32).max();
        let min_y = rasters.iter().map(|(r, _, dy)| r.min_y + dy).min();
        let max_y = rasters.iter().map(|(r, _, dy)| r.min_y + dy + r.height as i32).max();

        let uv_rect = match (sub_min, sub_max, min_y, max_y) {
            (Some(sub_min), Some(sub_max), Some(min_y), Some(max_y)) => {
                // As in `allocate_glyph`: whole pixels, with room for the
                // filter around the ink.
                let left = (sub_min - 2).div_euclid(3);
                let right = (sub_max + 4 + 2).div_euclid(3);
                let glyph_width = (right - left) as usize;
                let glyph_height = (max_y - min_y) as usize;
                let glyph_pos = {
                    let atlas = &mut self.atlas.lock();
                    let (pos, image) = atlas.allocate((MARGIN_LEFT + 3 * glyph_width + MARGIN_RIGHT, glyph_height));
                    let glyph_pos = (pos.0 + MARGIN_LEFT, pos.1);
                    // Overlapping strokes (a mark on its letter) cover as one
                    // shape would: combined as coverage first, then stored.
                    let sub_width = 3 * glyph_width;
                    let mut coverage = vec![0.0_f32; sub_width * glyph_height];
                    for (raster, dx, dy) in &rasters {
                        let x0 = (raster.min_x + dx - 3 * left) as usize;
                        let y0 = (raster.min_y + dy - min_y) as usize;
                        for y in 0..raster.height {
                            for x in 0..raster.width {
                                let v = raster.coverage[y * raster.width + x];
                                if 0.0 < v && x0 + x < sub_width {
                                    if let Some(c) = coverage.get_mut((y0 + y) * sub_width + x0 + x) {
                                        *c = 1.0 - (1.0 - *c) * (1.0 - v);
                                    }
                                }
                            }
                        }
                    }
                    for (i, &c) in coverage.iter().enumerate() {
                        if 0.0 < c {
                            image.set((glyph_pos.0 + i % sub_width, glyph_pos.1 + i / sub_width), c);
                        }
                    }
                    glyph_pos
                };
                UvRect {
                    offset: vec2(left as f32, min_y as f32) / self.pixels_per_point + self.y_offset_in_points * Vec2::Y,
                    size: vec2(glyph_width as f32, glyph_height as f32) / self.pixels_per_point,
                    min: [glyph_pos.0 as u16, glyph_pos.1 as u16],
                    max: [(glyph_pos.0 + 3 * glyph_width) as u16, (glyph_pos.1 + glyph_height) as u16],
                    gray: self.gray,
                }
            }
            _ => UvRect::default(),
        };
        self.shaped_cache.write().insert(placed, uv_rect);
        uv_rect
    }
}

type FontIndex = usize;

// TODO(emilk): rename?
/// Wrapper over multiple [`FontImpl`] (e.g. a primary + fallbacks for emojis)
pub struct Font {
    fonts: Vec<Arc<FontImpl>>,

    /// Lazily calculated.
    characters: Option<BTreeMap<char, Vec<String>>>,

    replacement_glyph: (FontIndex, GlyphInfo),
    pixels_per_point: f32,
    row_height: f32,
    glyph_info_cache: ahash::HashMap<char, (FontIndex, GlyphInfo)>,
}

impl Font {
    pub fn new(fonts: Vec<Arc<FontImpl>>) -> Self {
        if fonts.is_empty() {
            return Self {
                fonts,
                characters: None,
                replacement_glyph: Default::default(),
                pixels_per_point: 1.0,
                row_height: 0.0,
                glyph_info_cache: Default::default(),
            };
        }

        let pixels_per_point = fonts[0].pixels_per_point();
        let row_height = fonts[0].row_height();

        let mut slf = Self {
            fonts,
            characters: None,
            replacement_glyph: Default::default(),
            pixels_per_point,
            row_height,
            glyph_info_cache: Default::default(),
        };

        const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square
        const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback

        let replacement_glyph = slf
            .glyph_info_no_cache_or_fallback(PRIMARY_REPLACEMENT_CHAR)
            .or_else(|| slf.glyph_info_no_cache_or_fallback(FALLBACK_REPLACEMENT_CHAR))
            .unwrap_or_else(|| {
                #[cfg(feature = "log")]
                log::warn!(
                    "Failed to find replacement characters {PRIMARY_REPLACEMENT_CHAR:?} or {FALLBACK_REPLACEMENT_CHAR:?}. Will use empty glyph."
                );
                (0, GlyphInfo::default())
            });
        slf.replacement_glyph = replacement_glyph;

        slf
    }

    pub fn preload_characters(&mut self, s: &str) {
        for c in s.chars() {
            self.glyph_info(c);
        }
    }

    pub fn preload_common_characters(&mut self) {
        // Preload the printable ASCII characters [32, 126] (which excludes control codes):
        const FIRST_ASCII: usize = 32; // 32 == space
        const LAST_ASCII: usize = 126;
        for c in (FIRST_ASCII..=LAST_ASCII).map(|c| c as u8 as char) {
            self.glyph_info(c);
        }
        self.glyph_info('°');
        self.glyph_info(crate::text::PASSWORD_REPLACEMENT_CHAR);
    }

    /// RustCord: the first font of the family that draws `c` (see
    /// [`FontImpl::covers`]).
    pub(crate) fn font_impl_for(&self, c: char) -> Option<&FontImpl> {
        self.fonts.iter().find(|font| font.covers(c)).map(|font| &**font)
    }

    /// All supported characters, and in which font they are available in.
    pub fn characters(&mut self) -> &BTreeMap<char, Vec<String>> {
        self.characters.get_or_insert_with(|| {
            let mut characters: BTreeMap<char, Vec<String>> = Default::default();
            for font in &self.fonts {
                for chr in font.characters() {
                    characters.entry(chr).or_default().push(font.name.clone());
                }
            }
            characters
        })
    }

    #[inline(always)]
    pub fn round_to_pixel(&self, point: f32) -> f32 {
        (point * self.pixels_per_point).round() / self.pixels_per_point
    }

    /// Height of one row of text. In points
    #[inline(always)]
    pub fn row_height(&self) -> f32 {
        self.row_height
    }

    pub fn uv_rect(&self, c: char) -> UvRect {
        self.glyph_info_cache
            .get(&c)
            .map(|gi| gi.1.uv_rect)
            .unwrap_or_default()
    }

    /// Width of this character in points.
    pub fn glyph_width(&mut self, c: char) -> f32 {
        self.glyph_info(c).1.advance_width
    }

    /// Can we display this glyph?
    pub fn has_glyph(&mut self, c: char) -> bool {
        self.glyph_info(c) != self.replacement_glyph // TODO(emilk): this is a false negative if the user asks about the replacement character itself 🤦‍♂️
    }

    /// Can we display all the glyphs in this text?
    pub fn has_glyphs(&mut self, s: &str) -> bool {
        s.chars().all(|c| self.has_glyph(c))
    }

    /// `\n` will (intentionally) show up as the replacement character.
    fn glyph_info(&mut self, c: char) -> (FontIndex, GlyphInfo) {
        if let Some(font_index_glyph_info) = self.glyph_info_cache.get(&c) {
            return *font_index_glyph_info;
        }

        let font_index_glyph_info = self.glyph_info_no_cache_or_fallback(c);
        let font_index_glyph_info = font_index_glyph_info.unwrap_or(self.replacement_glyph);
        self.glyph_info_cache.insert(c, font_index_glyph_info);
        font_index_glyph_info
    }

    #[inline]
    pub(crate) fn font_impl_and_glyph_info(&mut self, c: char) -> (Option<&FontImpl>, GlyphInfo) {
        if self.fonts.is_empty() {
            return (None, self.replacement_glyph.1);
        }
        let (font_index, glyph_info) = self.glyph_info(c);
        let font_impl = &self.fonts[font_index];
        (Some(font_impl), glyph_info)
    }

    pub(crate) fn ascent(&self) -> f32 {
        if let Some(first) = self.fonts.first() {
            first.ascent()
        } else {
            self.row_height
        }
    }

    fn glyph_info_no_cache_or_fallback(&mut self, c: char) -> Option<(FontIndex, GlyphInfo)> {
        for (font_index, font_impl) in self.fonts.iter().enumerate() {
            if let Some(glyph_info) = font_impl.glyph_info(c) {
                self.glyph_info_cache.insert(c, (font_index, glyph_info));
                return Some((font_index, glyph_info));
            }
        }
        None
    }
}

/// Code points that will always be invisible (zero width).
///
/// See also [`FontImpl::ignore_character`].
#[inline]
fn invisible_char(c: char) -> bool {
    if c == '\r' {
        // A character most vile and pernicious. Don't display it.
        return true;
    }

    // See https://github.com/emilk/egui/issues/336

    // From https://www.fileformat.info/info/unicode/category/Cf/list.htm

    // TODO(emilk): heed bidi characters

    matches!(
        c,
        '\u{200B}' // ZERO WIDTH SPACE
            | '\u{200C}' // ZERO WIDTH NON-JOINER
            | '\u{200D}' // ZERO WIDTH JOINER
            | '\u{200E}' // LEFT-TO-RIGHT MARK
            | '\u{200F}' // RIGHT-TO-LEFT MARK
            | '\u{202A}' // LEFT-TO-RIGHT EMBEDDING
            | '\u{202B}' // RIGHT-TO-LEFT EMBEDDING
            | '\u{202C}' // POP DIRECTIONAL FORMATTING
            | '\u{202D}' // LEFT-TO-RIGHT OVERRIDE
            | '\u{202E}' // RIGHT-TO-LEFT OVERRIDE
            | '\u{2060}' // WORD JOINER
            | '\u{2061}' // FUNCTION APPLICATION
            | '\u{2062}' // INVISIBLE TIMES
            | '\u{2063}' // INVISIBLE SEPARATOR
            | '\u{2064}' // INVISIBLE PLUS
            | '\u{2066}' // LEFT-TO-RIGHT ISOLATE
            | '\u{2067}' // RIGHT-TO-LEFT ISOLATE
            | '\u{2068}' // FIRST STRONG ISOLATE
            | '\u{2069}' // POP DIRECTIONAL ISOLATE
            | '\u{206A}' // INHIBIT SYMMETRIC SWAPPING
            | '\u{206B}' // ACTIVATE SYMMETRIC SWAPPING
            | '\u{206C}' // INHIBIT ARABIC FORM SHAPING
            | '\u{206D}' // ACTIVATE ARABIC FORM SHAPING
            | '\u{206E}' // NATIONAL DIGIT SHAPES
            | '\u{206F}' // NOMINAL DIGIT SHAPES
            | '\u{FEFF}' // ZERO WIDTH NO-BREAK SPACE
    )
}

/// RustCord: the x-advance adjustment for a glyph pair from the font's GPOS
/// `kern` feature, in font units. `None` when the font has no GPOS kerning
/// (the caller then falls back to the `kern` table).
fn gpos_kern(data: &[u8], first: u16, second: u16) -> Option<i16> {
    use ttf_parser::gpos::{PairAdjustment, PositioningSubtable};
    let face = ttf_parser::Face::parse(data, 0).ok()?;
    let gpos = face.tables().gpos?;
    let kern = ttf_parser::Tag::from_bytes(b"kern");
    let (first, second) = (ttf_parser::GlyphId(first), ttf_parser::GlyphId(second));
    let mut found = false;
    for feature in gpos.features {
        if feature.tag != kern {
            continue;
        }
        found = true;
        for index in feature.lookup_indices {
            let Some(lookup) = gpos.lookups.get(index) else { continue };
            for subtable in lookup.subtables.into_iter::<PositioningSubtable<'_>>() {
                let PositioningSubtable::Pair(pair) = subtable else { continue };
                let records = match pair {
                    PairAdjustment::Format1 { coverage, sets } => coverage
                        .get(first)
                        .and_then(|i| sets.get(i))
                        .and_then(|set| set.get(second)),
                    PairAdjustment::Format2 { coverage, classes, matrix } => coverage
                        .get(first)
                        .and_then(|_| matrix.get((classes.0.get(first), classes.1.get(second)))),
                };
                // The first subtable that covers the pair decides, as in OpenType.
                if let Some((value, _)) = records {
                    return Some(value.x_advance);
                }
            }
        }
    }
    found.then_some(0)
}