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