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#[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
48pub 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 #[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 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#[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 #[must_use]
94 pub fn new(codepoint: u32) -> Self {
95 GlyphID { code: codepoint as u16, type_: GlyphIDType::FontPBF }
96 }
97
98 #[must_use]
101 pub fn from_char(c: char) -> Option<Self> {
102 pbf_code(c).map(GlyphID::from)
103 }
104
105 #[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 #[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 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#[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#[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 pub is_double_resolution: bool,
171}
172
173#[derive(Clone, PartialEq, Debug, Default, mln_wire::Wire)]
175pub struct Glyph {
176 pub id: GlyphID,
177 pub bitmap: AlphaImage,
179 pub metrics: GlyphMetrics,
180}
181
182impl Glyph {
183 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#[derive(Clone, Debug, Default, PartialEq)]
195pub struct PositionedGlyph {
196 pub glyph: GlyphID,
197 pub x: f32,
198 pub y: f32,
199 pub vertical: bool,
202 pub scale: f32,
203 pub rect: RectU16,
205 pub metrics: GlyphMetrics,
206 pub image_id: Option<String>,
208 pub section_index: usize,
210}
211
212#[derive(Clone, Debug, Default, PartialEq)]
214pub struct PositionedLine {
215 pub glyphs: Vec<PositionedGlyph>,
216 pub line_offset: f32,
219}
220
221#[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#[derive(Clone, Debug, Default, PartialEq)]
245pub struct Shaping {
246 pub lines: Vec<PositionedLine>,
247 pub bounds: Bounds,
249 pub verticalizable: bool,
251 pub icons_in_text: bool,
253}
254
255impl Shaping {
256 pub const Y_OFFSET: f32 = -17.0;
259
260 #[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#[derive(Clone)]
274pub struct FontData {
275 bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
276 face_index: u32,
277}
278
279impl FontData {
280 pub fn new(bytes: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
282 FontData { bytes, face_index: 0 }
283 }
284
285 #[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 #[must_use]
298 pub fn face_index(&self) -> u32 {
299 self.face_index
300 }
301
302 #[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 f.debug_struct("FontData").field("face_index", &self.face_index).finish_non_exhaustive()
331 }
332}
333
334impl 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#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
347pub struct FontFace {
348 pub type_: GlyphIDType,
350 pub name: String,
352 pub url: String,
353 pub ranges: Vec<FontFaceRange>,
355 #[wire(skip)]
359 pub data: Option<FontData>,
360 #[wire(skip, default = "regular_weight")]
363 pub weight: u16,
364}
365
366fn 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 #[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 #[must_use]
400 pub fn system(ranges: Vec<FontFaceRange>) -> Self {
401 FontFace { type_: GlyphIDType::SYSTEM, ..FontFace::new("", "", ranges) }
402 }
403
404 #[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 #[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
433impl 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#[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
468pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
480pub struct GlyphPosition {
481 pub rect: RectU16,
482 pub metrics: GlyphMetrics,
483}
484
485pub type GlyphPositions = VecMap<FontStackHash, BTreeMap<GlyphID, Option<GlyphPosition>>>;
488
489type FaceKey = (String, String, Vec<FontFaceRange>);
491
492struct 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
501pub 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 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 #[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}