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"))]
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 type_: GlyphIDType,
62}
63
64impl GlyphRange {
65 #[must_use]
67 pub fn new(first: u16, second: u16, type_: GlyphIDType) -> Self {
68 GlyphRange { first, second, 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)]
88pub struct GlyphID {
89 pub code: u16,
90 pub(crate) type_: GlyphIDType,
91}
92
93impl GlyphID {
94 #[must_use]
96 pub const fn new(code: u16) -> Self {
97 GlyphID { code, type_: GlyphIDType::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, type_: GlyphIDType) -> Self {
116 GlyphID { code: index, type_ }
117 }
118
119 #[must_use]
121 pub(crate) fn hash(self) -> u32 {
122 (u32::from(self.type_.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.type_)
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 type_: GlyphIDType,
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 type_: GlyphIDType::FontPBF,
375 name: name.to_string(),
376 url: url.to_string(),
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 { type_: GlyphIDType::SYSTEM, ..FontFace::new("", "", ranges) }
392 }
393
394 #[must_use]
402 pub fn device(url: &str, weight: u16, data: FontData) -> Self {
403 FontFace {
404 type_: 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 type_: 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<GlyphIDType, BTreeSet<Vec<char>>>>;
455
456pub type ShapeResults = VecMap<FontStack, VecMap<GlyphIDType, 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]) -> GlyphIDType {
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 GlyphIDType::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 GlyphIDType::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, GlyphIDType::FontPBF);
516 let b = GlyphID::with_type(0, GlyphIDType::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::<GlyphIDType>(), 2);
535 assert_eq!(size_of::<GlyphID>(), 4);
536 }
537
538 #[test]
539 fn face_types_are_stable_per_key() {
540 let fs = "Noto Sans Regular";
541 let a = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
542 let b = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
543 let c = face_type("local://b.ttf", fs, &[(0x1780, 0x17FF)]);
544 assert_eq!(a, b);
545 assert_ne!(a, c);
546 assert_ne!(a, GlyphIDType::FontPBF);
547 }
548
549 #[test]
550 fn style_faces_come_before_fallback_faces() {
551 let style_face = mln_style::font_face::FontFace {
552 name: "Noto Sans Regular".to_owned(),
553 url: "local://a.ttf".to_owned(),
554 ranges: vec![(0x1000, 0x109F)],
555 };
556 let fallback = vec![FontFace::system(vec![(0x0900, 0x097F)])];
557
558 assert_eq!(style_font_faces(None, None), None);
559 assert_eq!(style_font_faces(None, Some(&Vec::new())), None);
560 assert_eq!(style_font_faces(Some(&Vec::new()), None), Some(Arc::new(Vec::new())));
561
562 let faces = style_font_faces(Some(&vec![style_face.clone()]), Some(&fallback)).unwrap();
563 assert_eq!(faces.len(), 2);
564 assert_eq!(faces[0].name, style_face.name);
565 assert_eq!(faces[0].type_, face_type(&style_face.url, &style_face.name, &style_face.ranges));
566 assert_eq!(faces[1], fallback[0]);
567 }
568}