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 GlyphIDType {
17 #[default]
18 FontPBF,
19 Face(NonZeroU16),
20}
21
22impl GlyphIDType {
23 pub const SYSTEM: GlyphIDType = GlyphIDType::Face(NonZeroU16::MAX);
30
31 #[must_use]
33 pub const fn face(id: NonZeroU16) -> Self {
34 GlyphIDType::Face(id)
35 }
36
37 #[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#[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 #[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 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#[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 #[must_use]
97 pub fn new(codepoint: u32) -> Self {
98 GlyphID { code: codepoint as u16, type_: GlyphIDType::FontPBF }
99 }
100
101 #[must_use]
104 pub fn from_char(c: char) -> Option<Self> {
105 pbf_code(c).map(GlyphID::from)
106 }
107
108 #[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 #[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 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#[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#[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 pub is_double_resolution: bool,
174}
175
176#[derive(Clone, PartialEq, Debug, Default, mln_wire::Wire)]
178pub struct Glyph {
179 pub id: GlyphID,
180 pub bitmap: AlphaImage,
182 pub metrics: GlyphMetrics,
183}
184
185impl Glyph {
186 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#[derive(Clone, Debug, Default, PartialEq)]
198pub struct PositionedGlyph {
199 pub glyph: GlyphID,
200 pub x: f32,
201 pub y: f32,
202 pub vertical: bool,
205 pub scale: f32,
206 pub rect: RectU16,
208 pub metrics: GlyphMetrics,
209 pub image_id: Option<String>,
211 pub section_index: usize,
213}
214
215#[derive(Clone, Debug, Default, PartialEq)]
217pub struct PositionedLine {
218 pub glyphs: Vec<PositionedGlyph>,
219 pub line_offset: f32,
222}
223
224#[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#[derive(Clone, Debug, Default, PartialEq)]
248pub struct Shaping {
249 pub lines: Vec<PositionedLine>,
250 pub bounds: Bounds,
252 pub verticalizable: bool,
254 pub icons_in_text: bool,
256}
257
258impl Shaping {
259 pub const Y_OFFSET: f32 = -17.0;
262
263 #[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#[derive(Clone)]
277pub struct FontData {
278 bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
279 face_index: u32,
280}
281
282impl FontData {
283 pub(crate) fn new(bytes: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
285 FontData { bytes, face_index: 0 }
286 }
287
288 #[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 #[must_use]
301 pub fn face_index(&self) -> u32 {
302 self.face_index
303 }
304
305 #[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 f.debug_struct("FontData").field("face_index", &self.face_index).finish_non_exhaustive()
334 }
335}
336
337impl 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#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
350pub struct FontFace {
351 pub type_: GlyphIDType,
353 pub name: String,
355 pub(crate) url: String,
356 pub ranges: Vec<FontFaceRange>,
358 #[wire(skip)]
362 pub(crate) data: Option<FontData>,
363 #[wire(skip, default = "regular_weight")]
366 pub(crate) weight: u16,
367}
368
369fn 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 #[must_use]
394 pub fn system(ranges: Vec<FontFaceRange>) -> Self {
395 FontFace { type_: GlyphIDType::SYSTEM, ..FontFace::new("", "", ranges) }
396 }
397
398 #[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 #[must_use]
416 pub(crate) fn with_data(mut self, data: FontData) -> Self {
417 self.data = Some(data);
418 self
419 }
420}
421
422impl 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#[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
457pub(crate) type ShapeRequests = VecMap<FontStack, VecMap<GlyphIDType, BTreeSet<Vec<char>>>>;
459
460pub type ShapeResults = VecMap<FontStack, VecMap<GlyphIDType, BTreeMap<Vec<char>, Arc<crate::text::ShapedText>>>>;
463
464#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
468pub struct GlyphDependencies {
469 pub glyphs: VecMap<FontStack, GlyphIDs>,
470 pub shapes: ShapeRequests,
471}
472
473#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
476pub struct GlyphPosition {
477 pub rect: RectU16,
478 pub metrics: GlyphMetrics,
479}
480
481pub type GlyphPositions = VecMap<FontStackHash, BTreeMap<GlyphID, Option<GlyphPosition>>>;
484
485type FaceKey = (String, String, Vec<FontFaceRange>);
487
488struct 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
497pub(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 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 #[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}