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#[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 pub const SYSTEM: GlyphFont = GlyphFont::Face(NonZeroU16::MAX);
30
31 #[must_use]
33 pub const fn face(id: NonZeroU16) -> Self {
34 GlyphFont::Face(id)
35 }
36
37 #[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#[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 #[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 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#[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 #[must_use]
96 pub const fn new(code: u16) -> Self {
97 GlyphID { code, font: GlyphFont::FontPBF }
98 }
99
100 #[must_use]
103 pub fn from_char(c: char) -> Option<Self> {
104 pbf_code(c).map(GlyphID::from)
105 }
106
107 #[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 #[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 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#[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#[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 pub is_double_resolution: bool,
170}
171
172#[derive(Clone, PartialEq, Debug, Default, mln_wire::Wire)]
174pub struct Glyph {
175 pub id: GlyphID,
176 pub bitmap: AlphaImage,
178 pub metrics: GlyphMetrics,
179}
180
181impl Glyph {
182 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#[derive(Clone, Debug, Default, PartialEq)]
194pub struct PositionedGlyph {
195 pub glyph: GlyphID,
196 pub x: f32,
197 pub y: f32,
198 pub vertical: bool,
201 pub scale: f32,
202 pub rect: RectU16,
204 pub metrics: GlyphMetrics,
205 pub image_id: Option<String>,
207 pub section_index: usize,
209}
210
211#[derive(Clone, Debug, Default, PartialEq)]
213pub struct PositionedLine {
214 pub glyphs: Vec<PositionedGlyph>,
215 pub line_offset: f32,
218}
219
220#[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#[derive(Clone, Debug, Default, PartialEq)]
244pub struct Shaping {
245 pub lines: Vec<PositionedLine>,
246 pub bounds: Bounds,
248 pub verticalizable: bool,
250 pub icons_in_text: bool,
252}
253
254impl Shaping {
255 pub const Y_OFFSET: f32 = -17.0;
258
259 #[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#[derive(Clone)]
273pub struct FontData {
274 bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
275 face_index: u32,
276}
277
278impl FontData {
279 pub(crate) fn new(bytes: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
281 FontData { bytes, face_index: 0 }
282 }
283
284 #[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 #[must_use]
297 pub fn face_index(&self) -> u32 {
298 self.face_index
299 }
300
301 #[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 f.debug_struct("FontData").field("face_index", &self.face_index).finish_non_exhaustive()
330 }
331}
332
333impl 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#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
346pub struct FontFace {
347 pub font: GlyphFont,
349 pub name: String,
351 pub(crate) url: String,
352 pub ranges: Vec<FontFaceRange>,
354 #[wire(skip)]
358 pub(crate) data: Option<FontData>,
359 #[wire(skip, default = "regular_weight")]
362 pub(crate) weight: u16,
363}
364
365fn 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 #[must_use]
390 pub fn system(ranges: Vec<FontFaceRange>) -> Self {
391 FontFace { font: GlyphFont::SYSTEM, ..FontFace::new("", "", ranges) }
392 }
393
394 #[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 #[must_use]
412 pub(crate) fn with_data(mut self, data: FontData) -> Self {
413 self.data = Some(data);
414 self
415 }
416}
417
418impl 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#[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
453pub(crate) type ShapeRequests = VecMap<FontStack, VecMap<GlyphFont, BTreeSet<Vec<char>>>>;
455
456pub type ShapeResults = VecMap<FontStack, VecMap<GlyphFont, BTreeMap<Vec<char>, Arc<crate::text::ShapedText>>>>;
459
460#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
464pub struct GlyphDependencies {
465 pub glyphs: VecMap<FontStack, GlyphIDs>,
466 pub shapes: ShapeRequests,
467}
468
469#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
472pub struct GlyphPosition {
473 pub rect: RectU16,
474 pub metrics: GlyphMetrics,
475}
476
477pub type GlyphPositions = VecMap<FontStackHash, BTreeMap<GlyphID, Option<GlyphPosition>>>;
480
481type FaceKey = (String, String, Vec<FontFaceRange>);
483
484struct 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
493pub(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 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 #[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 #[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}