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