Skip to main content

mln_engine/text/
glyph.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::num::NonZeroU16;
3use std::sync::Arc;
4
5use mln_style::bitmap::AlphaImage;
6use mln_style::collections::VecMap;
7use parking_lot::Mutex;
8
9use crate::text::atlas::RectU16;
10use crate::text::font_stack::FontStack;
11use crate::text::tagged_string::FontStackHash;
12
13/// Where a glyph comes from: glyph PBFs, or a font file that shapes text,
14/// numbered at runtime (`face_type`).
15#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, mln_wire::Wire)]
16pub enum GlyphFont {
17    #[default]
18    FontPBF,
19    Face(NonZeroU16),
20}
21
22impl GlyphFont {
23    /// Text whose fonts the device chooses per character
24    /// ([`FontFace::system`]): the glyph store has the renderer's
25    /// [`FontChooser`](crate::text::local_fonts::FontChooser) choose a face for
26    /// each piece, and its glyphs take those faces' fonts. No glyph has this
27    /// font, and no face its number. A constant rather than a variant, so
28    /// that a font stays a `u16`.
29    pub const SYSTEM: GlyphFont = GlyphFont::Face(NonZeroU16::MAX);
30
31    /// The font file numbered `id`.
32    #[must_use]
33    pub const fn face(id: NonZeroU16) -> Self {
34        GlyphFont::Face(id)
35    }
36
37    /// The font's number as stored in a glyph ID's upper half: 0 for
38    /// `FontPBF`.
39    #[must_use]
40    pub const fn id(self) -> u16 {
41        match self {
42            GlyphFont::FontPBF => 0,
43            GlyphFont::Face(id) => id.get(),
44        }
45    }
46}
47
48/// The glyphs in a glyph PBF range, and the ranges of a font stack: all of
49/// them, and those that aren't entirely ideographs, which are drawn locally.
50#[cfg(any(test, feature = "sqlite"))]
51pub(crate) const GLYPHS_PER_GLYPH_RANGE: u32 = 256;
52#[cfg(any(test, feature = "sqlite"))]
53pub(crate) const GLYPH_RANGES_PER_FONT_STACK: u32 = 256;
54#[cfg(any(test, feature = "sqlite"))]
55pub(crate) const NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK: u32 = 97;
56
57#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
58pub struct GlyphRange {
59    pub first: u16,
60    pub second: u16,
61    pub font: GlyphFont,
62}
63
64impl GlyphRange {
65    /// The range `first..=second` of `font`.
66    #[must_use]
67    pub fn new(first: u16, second: u16, font: GlyphFont) -> Self {
68        GlyphRange { first, second, font }
69    }
70}
71
72impl PartialOrd for GlyphRange {
73    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
74        Some(self.cmp(other))
75    }
76}
77
78impl Ord for GlyphRange {
79    /// Orders by first, then second, then type.
80    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
81        (self.first, self.second, self.font).cmp(&(other.first, other.second, other.font))
82    }
83}
84
85/// A glyph: `code` (a BMP character in glyph PBFs, or a font's glyph index)
86/// and `type`. Glyphs order by `hash`, the two as one `u32`.
87#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, mln_wire::Wire)]
88pub struct GlyphID {
89    pub code: u16,
90    pub(crate) font: GlyphFont,
91}
92
93impl GlyphID {
94    /// The glyph PBF glyph with `code`, a BMP code point.
95    #[must_use]
96    pub const fn new(code: u16) -> Self {
97        GlyphID { code, font: GlyphFont::FontPBF }
98    }
99
100    /// The glyph PBF glyph of `c`. Glyph PBFs only cover the BMP, so a
101    /// character beyond it has none.
102    #[must_use]
103    pub fn from_char(c: char) -> Option<Self> {
104        pbf_code(c).map(GlyphID::from)
105    }
106
107    /// The character that a glyph PBF glyph stands for; `None` for a
108    /// surrogate code.
109    #[must_use]
110    pub(crate) fn char(self) -> Option<char> {
111        char::from_u32(u32::from(self.code))
112    }
113
114    #[must_use]
115    pub fn with_type(index: u16, font: GlyphFont) -> Self {
116        GlyphID { code: index, font }
117    }
118
119    /// The type in the high 16 bits and the code in the low ones.
120    #[must_use]
121    pub(crate) fn hash(self) -> u32 {
122        (u32::from(self.font.id()) << 16) | u32::from(self.code)
123    }
124}
125
126impl PartialOrd for GlyphID {
127    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
128        Some(self.cmp(other))
129    }
130}
131
132impl Ord for GlyphID {
133    /// Compares `hash`.
134    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
135        self.hash().cmp(&other.hash())
136    }
137}
138
139impl From<u16> for GlyphID {
140    fn from(code: u16) -> Self {
141        GlyphID::new(code)
142    }
143}
144
145/// The code of `c`'s glyph in glyph PBFs, which only cover the BMP.
146#[must_use]
147pub(crate) fn pbf_code(c: char) -> Option<u16> {
148    u16::try_from(u32::from(c)).ok()
149}
150
151pub(crate) type GlyphIDs = BTreeSet<GlyphID>;
152
153/// The 256-glyph range that contains `glyph`. Only works for the BMP.
154#[must_use]
155pub fn glyph_range(glyph: GlyphID) -> GlyphRange {
156    let start = glyph.code & 0xff00;
157    GlyphRange::new(start, start | 0xff, glyph.font)
158}
159
160#[derive(Clone, Copy, PartialEq, Debug, Default, mln_wire::Wire)]
161pub struct GlyphMetrics {
162    pub width: u32,
163    pub height: u32,
164    pub left: f32,
165    pub top: f32,
166    pub advance: u32,
167    /// True when the glyph bitmap is rendered at 2x texture resolution
168    /// (e.g. local CJK glyphs).
169    pub is_double_resolution: bool,
170}
171
172/// A glyph's bitmap and metrics.
173#[derive(Clone, PartialEq, Debug, Default, mln_wire::Wire)]
174pub struct Glyph {
175    pub id: GlyphID,
176    /// A signed distance field of the glyph with a border (see `BORDER_SIZE`).
177    pub bitmap: AlphaImage,
178    pub metrics: GlyphMetrics,
179}
180
181impl Glyph {
182    /// The SDF border around each glyph bitmap. We're using this value
183    /// throughout the Mapbox GL ecosystem. If this is different, the glyphs
184    /// also need to be reencoded.
185    pub(crate) const BORDER_SIZE: u8 = 3;
186}
187
188pub(crate) type Glyphs = BTreeMap<GlyphID, Option<Arc<Glyph>>>;
189pub type GlyphMap = VecMap<FontStackHash, Glyphs>;
190
191/// A glyph or an inline image of a shaped label, placed relative to the
192/// label's anchor, in pixels at a font size of `ONE_EM`.
193#[derive(Clone, Debug, Default, PartialEq)]
194pub struct PositionedGlyph {
195    pub glyph: GlyphID,
196    pub x: f32,
197    pub y: f32,
198    /// Whether the glyph stands upright in a vertical line rather than
199    /// turning with it.
200    pub vertical: bool,
201    pub scale: f32,
202    /// Where the glyph or image is in its atlas.
203    pub rect: RectU16,
204    pub metrics: GlyphMetrics,
205    /// The image an image section draws.
206    pub image_id: Option<String>,
207    /// The index of the glyph's section in its `TaggedString`.
208    pub section_index: usize,
209}
210
211/// A line of a shaped label.
212#[derive(Clone, Debug, Default, PartialEq)]
213pub struct PositionedLine {
214    pub glyphs: Vec<PositionedGlyph>,
215    /// How far the line's content reaches below a line of `ONE_EM` glyphs:
216    /// its largest section's growth beyond one em, or an inline image's.
217    pub line_offset: f32,
218}
219
220/// A box around a label's anchor: its edges' offsets from the anchor, with y
221/// down.
222#[derive(Clone, Copy, Debug, Default, PartialEq)]
223pub struct Bounds {
224    pub left: f32,
225    pub top: f32,
226    pub right: f32,
227    pub bottom: f32,
228}
229
230impl Bounds {
231    #[must_use]
232    pub fn width(&self) -> f32 {
233        self.right - self.left
234    }
235
236    #[must_use]
237    pub fn height(&self) -> f32 {
238        self.bottom - self.top
239    }
240}
241
242/// A label's text, broken into lines and placed glyph by glyph.
243#[derive(Clone, Debug, Default, PartialEq)]
244pub struct Shaping {
245    pub lines: Vec<PositionedLine>,
246    /// The box the text takes, moved by the layout's offset.
247    pub bounds: Bounds,
248    /// Whether a glyph stands upright, as in vertical text.
249    pub verticalizable: bool,
250    /// Whether the text holds an inline image.
251    pub icons_in_text: bool,
252}
253
254impl Shaping {
255    /// The y of a label's first line before alignment moves it, which suits
256    /// glyph PBFs' metrics. It belongs in the font's metadata.
257    pub const Y_OFFSET: f32 = -17.0;
258
259    /// Whether no line has a glyph.
260    #[must_use]
261    pub fn is_empty(&self) -> bool {
262        self.lines.iter().all(|line| line.glyphs.is_empty())
263    }
264}
265
266pub(crate) use mln_style::font_face::FontFaceRange;
267
268/// The bytes of a font file that an app already holds, such as a
269/// memory-mapped file, shared without a copy, and which of its faces to use.
270/// A font face's file can be TrueType or OpenType, a collection of them, WOFF
271/// or WOFF2.
272#[derive(Clone)]
273pub struct FontData {
274    bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
275    face_index: u32,
276}
277
278impl FontData {
279    /// The file's first face.
280    pub(crate) fn new(bytes: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
281        FontData { bytes, face_index: 0 }
282    }
283
284    /// Face `index` of a collection, rather than its first.
285    #[must_use]
286    pub fn with_face_index(self, index: u32) -> Self {
287        FontData { face_index: index, ..self }
288    }
289
290    #[must_use]
291    pub fn as_bytes(&self) -> &[u8] {
292        (*self.bytes).as_ref()
293    }
294
295    /// Which face of a collection to use: 0 for a file of one face.
296    #[must_use]
297    pub fn face_index(&self) -> u32 {
298        self.face_index
299    }
300
301    /// The same bytes, for readers that take any shared bytes.
302    #[must_use]
303    pub(crate) fn shared(&self) -> Arc<dyn AsRef<[u8]> + Send + Sync> {
304        Arc::clone(&self.bytes)
305    }
306}
307
308impl Default for FontData {
309    fn default() -> Self {
310        FontData::from(Vec::new())
311    }
312}
313
314impl From<Vec<u8>> for FontData {
315    fn from(bytes: Vec<u8>) -> Self {
316        FontData::new(Arc::new(bytes))
317    }
318}
319
320impl From<Arc<Vec<u8>>> for FontData {
321    fn from(bytes: Arc<Vec<u8>>) -> Self {
322        FontData::new(bytes)
323    }
324}
325
326impl std::fmt::Debug for FontData {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        // Not the bytes: they may load on first access.
329        f.debug_struct("FontData").field("face_index", &self.face_index).finish_non_exhaustive()
330    }
331}
332
333/// Equal when both share the same bytes and use the same face.
334impl PartialEq for FontData {
335    fn eq(&self, other: &Self) -> bool {
336        Arc::ptr_eq(&self.bytes, &other.bytes) && self.face_index == other.face_index
337    }
338}
339
340/// A font file that draws a font's characters in `ranges`, from a style's
341/// `font-faces` or an app's fallback faces. A face without a name is a
342/// fallback, which every font stack uses after the faces that name one of
343/// its fonts: in a style with glyph PBFs, for the text they can't shape; or
344/// one of the device's fonts ([`FontFace::device`]), which has no ranges.
345#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
346pub struct FontFace {
347    /// The type of the face's glyphs.
348    pub font: GlyphFont,
349    /// The `text-font` name it draws, or "" for a fallback.
350    pub name: String,
351    pub(crate) url: String,
352    /// The code points it draws, first and last.
353    pub ranges: Vec<FontFaceRange>,
354    /// The font file itself, which the map then uses instead of fetching
355    /// `url`. Left out of the faces that workers get, which don't read
356    /// font files.
357    #[wire(skip)]
358    pub(crate) data: Option<FontData>,
359    /// The OpenType weight a variable font loads at: regular (400) unless
360    /// made at another. Left out of the faces that workers get, like `data`.
361    #[wire(skip, default = "regular_weight")]
362    pub(crate) weight: u16,
363}
364
365/// [`REGULAR_WEIGHT`](crate::text::weight::REGULAR_WEIGHT) as an OpenType weight.
366fn regular_weight() -> u16 {
367    crate::text::weight::REGULAR_WEIGHT as u16
368}
369
370impl FontFace {
371    #[must_use]
372    pub fn new(name: &str, url: &str, ranges: Vec<FontFaceRange>) -> Self {
373        FontFace {
374            font: GlyphFont::FontPBF,
375            name: name.to_owned(),
376            url: url.to_owned(),
377            ranges,
378            data: None,
379            weight: regular_weight(),
380        }
381    }
382
383    /// The device's fonts, as a fallback face: in a style with glyph PBFs,
384    /// for the text in `ranges` (the scripts the PBFs can't shape that the
385    /// device has fonts for); in a style without, for all the text the
386    /// style's own faces don't draw. For each character, the glyph store has
387    /// the renderer's [`FontChooser`](crate::text::local_fonts::FontChooser) choose
388    /// the face that draws it.
389    #[must_use]
390    pub fn system(ranges: Vec<FontFaceRange>) -> Self {
391        FontFace { font: GlyphFont::SYSTEM, ..FontFace::new("", "", ranges) }
392    }
393
394    /// One of the device's fonts, which a
395    /// [`FontChooser`](crate::text::local_fonts::FontChooser) chose, at the
396    /// OpenType `weight` its label's font name asks for. It has no name and
397    /// no ranges, holds its font file, and `url` only names it
398    /// (`file:///path#index`, or `font://PostScriptName` for a CoreText
399    /// font). The same url and weight get the same type for the life of the
400    /// process.
401    #[must_use]
402    pub fn device(url: &str, weight: u16, data: FontData) -> Self {
403        FontFace {
404            font: face_type(&format!("{url}@{weight}"), "", &[]),
405            weight,
406            ..FontFace::new("", url, Vec::new()).with_data(data)
407        }
408    }
409
410    /// The face with its font file in memory, so that `url` only names it.
411    #[must_use]
412    pub(crate) fn with_data(mut self, data: FontData) -> Self {
413        self.data = Some(data);
414        self
415    }
416}
417
418/// A style's face, or an app's fallback face without a name, with its glyph
419/// type.
420impl From<&mln_style::font_face::FontFace> for FontFace {
421    fn from(face: &mln_style::font_face::FontFace) -> Self {
422        FontFace {
423            font: face_type(&face.url, &face.name, &face.ranges),
424            ..FontFace::new(&face.name, &face.url, face.ranges.clone())
425        }
426    }
427}
428
429impl mln_style::font_face::FontCoverage for FontFace {
430    fn covers(&self, c: char) -> bool {
431        mln_style::font_face::ranges_cover(&self.ranges, c)
432    }
433}
434
435pub type FontFaces = Vec<FontFace>;
436
437/// The faces that a map draws a style's text with: the style's own
438/// `font-faces`, then `fallback`, the app's. `None` when the style has no
439/// `font-faces` and the app no fallback faces.
440#[must_use]
441pub(crate) fn style_font_faces(
442    style: Option<&mln_style::font_face::FontFaces>,
443    fallback: Option<&FontFaces>,
444) -> Option<Arc<FontFaces>> {
445    let fallback = fallback.filter(|faces| !faces.is_empty());
446    if style.is_none() && fallback.is_none() {
447        return None;
448    }
449    let style = style.into_iter().flatten().map(FontFace::from);
450    Some(Arc::new(style.chain(fallback.into_iter().flatten().cloned()).collect()))
451}
452
453/// The texts that each font face of each font stack shapes.
454pub(crate) type ShapeRequests = VecMap<FontStack, VecMap<GlyphFont, BTreeSet<Vec<char>>>>;
455
456/// Each font-face text of each font stack, shaped by its face: what
457/// `ShapeRequests` resolve to.
458pub type ShapeResults = VecMap<FontStack, VecMap<GlyphFont, BTreeMap<Vec<char>, Arc<crate::text::ShapedText>>>>;
459
460/// The glyphs and the shapings of text that a layout asks for: the
461/// glyphs of each font stack, by id, and the texts each font face of each
462/// font stack shapes.
463#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
464pub struct GlyphDependencies {
465    pub glyphs: VecMap<FontStack, GlyphIDs>,
466    pub shapes: ShapeRequests,
467}
468
469/// Where a glyph is in an atlas, and its metrics. A glyph without a bitmap
470/// (a space, say) has an empty `rect`.
471#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
472pub struct GlyphPosition {
473    pub rect: RectU16,
474    pub metrics: GlyphMetrics,
475}
476
477/// The glyphs of a layout's font stacks: `None` for one that no font has, or
478/// whose range failed to load.
479pub type GlyphPositions = VecMap<FontStackHash, BTreeMap<GlyphID, Option<GlyphPosition>>>;
480
481/// The font file, font and ranges a glyph type was handed out for.
482type FaceKey = (String, String, Vec<FontFaceRange>);
483
484/// The glyph types handed out, a few for each style: by what they were for,
485/// and the last one.
486struct FaceTypes {
487    last: u16,
488    types: Vec<(FaceKey, NonZeroU16)>,
489}
490
491static FACE_TYPES: Mutex<FaceTypes> = Mutex::new(FaceTypes { last: 0, types: Vec::new() });
492
493/// The glyph type of the face of the font file at `url` that draws `font`'s
494/// `ranges`: the same for the same three for the life of the process, and
495/// a new one otherwise, which after `u16::MAX - 1` types repeats the first.
496pub(crate) fn face_type(url: &str, font: &str, ranges: &[FontFaceRange]) -> GlyphFont {
497    let mut types = FACE_TYPES.lock();
498    let found = types.types.iter().find(|((u, f, r), _)| u == url && f == font && r == ranges);
499    if let Some(&(_, id)) = found {
500        return GlyphFont::Face(id);
501    }
502    // Neither 0 (`FontPBF`) nor `u16::MAX` (`SYSTEM`).
503    types.last = if types.last >= u16::MAX - 1 { 1 } else { types.last + 1 };
504    let id = NonZeroU16::new(types.last).unwrap_or(NonZeroU16::MIN);
505    types.types.push(((url.to_owned(), font.to_owned(), ranges.to_vec()), id));
506    GlyphFont::Face(id)
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    #[test]
514    fn glyph_id_order_is_the_union_hash() {
515        let a = GlyphID::with_type(0xFFFF, GlyphFont::FontPBF);
516        let b = GlyphID::with_type(0, GlyphFont::face(NonZeroU16::MIN));
517        assert!(a < b);
518        assert_eq!(b.hash(), 0x10000);
519        assert_eq!(GlyphID::from_char('\u{FFFF}'), Some(GlyphID::new(0xFFFF)));
520        assert_eq!(GlyphID::from_char('\u{1F600}'), None);
521    }
522
523    #[test]
524    fn glyph_range_is_the_256_glyphs_around_a_glyph() {
525        let r = glyph_range(GlyphID::new(0x41));
526        assert_eq!((r.first, r.second), (0, 255));
527        let r = glyph_range(GlyphID::new(0xFFFF));
528        assert_eq!((r.first, r.second), (65280, 65535));
529    }
530
531    // Layouts compare and hash glyph IDs by the million.
532    #[test]
533    fn a_glyph_id_is_two_u16s() {
534        assert_eq!(size_of::<GlyphFont>(), 2);
535        assert_eq!(size_of::<GlyphID>(), 4);
536    }
537
538    /// The offline download's estimate of a font stack's ranges counts those
539    /// that local fonts don't draw entirely.
540    #[test]
541    fn non_ideograph_ranges_are_the_ranges_local_fonts_dont_draw() {
542        let local = (0..GLYPH_RANGES_PER_FONT_STACK)
543            .filter(|i| mln_style::i18n::glyph_range_is_entirely_locally_generated((i * GLYPHS_PER_GLYPH_RANGE) as u16))
544            .count() as u32;
545        assert_eq!(GLYPH_RANGES_PER_FONT_STACK - local, NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK);
546    }
547
548    #[test]
549    fn face_types_are_stable_per_key() {
550        let fs = "Noto Sans Regular";
551        let a = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
552        let b = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
553        let c = face_type("local://b.ttf", fs, &[(0x1780, 0x17FF)]);
554        assert_eq!(a, b);
555        assert_ne!(a, c);
556        assert_ne!(a, GlyphFont::FontPBF);
557    }
558
559    #[test]
560    fn style_faces_come_before_fallback_faces() {
561        let style_face = mln_style::font_face::FontFace {
562            name: "Noto Sans Regular".to_owned(),
563            url: "local://a.ttf".to_owned(),
564            ranges: vec![(0x1000, 0x109F)],
565        };
566        let fallback = vec![FontFace::system(vec![(0x0900, 0x097F)])];
567
568        assert_eq!(style_font_faces(None, None), None);
569        assert_eq!(style_font_faces(None, Some(&Vec::new())), None);
570        assert_eq!(style_font_faces(Some(&Vec::new()), None), Some(Arc::new(Vec::new())));
571
572        let faces = style_font_faces(Some(&vec![style_face.clone()]), Some(&fallback)).unwrap();
573        assert_eq!(faces.len(), 2);
574        assert_eq!(faces[0].name, style_face.name);
575        assert_eq!(faces[0].font, face_type(&style_face.url, &style_face.name, &style_face.ranges));
576        assert_eq!(faces[1], fallback[0]);
577    }
578}