1use std::sync::{Mutex, OnceLock};
2
3use cosmic_text::{
4 Attrs, Buffer, CacheKey, Family, FontSystem, Metrics, Shaping, Style, SwashCache, SwashContent,
5 Weight,
6};
7use plotine_core::{PlotError, Point, Result};
8
9#[inline]
11fn quantize_size_px(size_px: f32) -> f32 {
12 size_px.round().max(1.0)
13}
14
15pub const EMBEDDED_FONT: &[u8] = include_bytes!("../fonts/DejaVuSans.ttf");
17pub const EMBEDDED_FONT_OBLIQUE: &[u8] = include_bytes!("../fonts/DejaVuSans-Oblique.ttf");
19pub const FONT_FAMILY: &str = "DejaVu Sans";
21
22fn font_system() -> &'static Mutex<FontSystem> {
23 static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
24 FONT_SYSTEM.get_or_init(|| {
25 let mut fs = FontSystem::new();
26 fs.db_mut().load_font_data(EMBEDDED_FONT.to_vec());
27 fs.db_mut().load_font_data(EMBEDDED_FONT_OBLIQUE.to_vec());
28 Mutex::new(fs)
29 })
30}
31
32pub(crate) fn with_font_system<T>(f: impl FnOnce(&mut FontSystem) -> Result<T>) -> Result<T> {
34 let mut fs = font_system()
35 .lock()
36 .map_err(|_| PlotError::text("font system lock poisoned"))?;
37 f(&mut fs)
38}
39
40#[derive(Debug, Clone)]
42pub struct GlyphImage {
43 pub x: i32,
44 pub y: i32,
45 pub width: u32,
46 pub height: u32,
47 pub content: GlyphContent,
48 pub data: Vec<u8>,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum GlyphContent {
53 Mask,
54 SubpixelMask,
55 Color,
56}
57
58pub struct TextEngine {
60 swash: SwashCache,
61}
62
63impl Default for TextEngine {
64 fn default() -> Self {
65 Self::new()
66 }
67}
68
69impl TextEngine {
70 pub fn new() -> Self {
71 let _ = font_system();
72 Self {
73 swash: SwashCache::new(),
74 }
75 }
76
77 fn attrs(italic: bool) -> Attrs<'static> {
78 let style = if italic { Style::Italic } else { Style::Normal };
79 Attrs::new()
80 .family(Family::Name(FONT_FAMILY))
81 .weight(Weight::NORMAL)
82 .style(style)
83 }
84
85 pub fn measure(&self, text: &str, size_px: f32) -> Result<(f64, f64)> {
86 self.measure_styled(text, size_px, false)
87 }
88
89 pub fn measure_styled(&self, text: &str, size_px: f32, italic: bool) -> Result<(f64, f64)> {
90 let size_px = quantize_size_px(size_px);
91 let mut fs = font_system()
92 .lock()
93 .map_err(|_| PlotError::text("font system lock poisoned"))?;
94 let metrics = Metrics::new(size_px, size_px * 1.2);
95 let mut buffer = Buffer::new(&mut fs, metrics);
96 buffer.set_text(&mut fs, text, &Self::attrs(italic), Shaping::Advanced);
97 buffer.shape_until_scroll(&mut fs, false);
98
99 let width = buffer
100 .layout_runs()
101 .map(|run| run.line_w as f64)
102 .fold(0.0_f64, f64::max);
103 let height = buffer
104 .layout_runs()
105 .map(|run| run.line_height as f64)
106 .sum::<f64>()
107 .max(size_px as f64);
108 Ok((width, height))
109 }
110
111 pub fn glyphs_at(
113 &mut self,
114 text: &str,
115 origin: Point,
116 size_px: f32,
117 ) -> Result<Vec<GlyphImage>> {
118 self.glyphs_at_styled(text, origin, size_px, false)
119 }
120
121 pub fn glyphs_at_styled(
122 &mut self,
123 text: &str,
124 origin: Point,
125 size_px: f32,
126 italic: bool,
127 ) -> Result<Vec<GlyphImage>> {
128 let size_px = quantize_size_px(size_px);
129 let mut fs = font_system()
130 .lock()
131 .map_err(|_| PlotError::text("font system lock poisoned"))?;
132 let metrics = Metrics::new(size_px, size_px * 1.2);
133 let mut buffer = Buffer::new(&mut fs, metrics);
134 buffer.set_size(&mut fs, Some(10_000.0), Some(size_px * 2.0));
135 buffer.set_text(&mut fs, text, &Self::attrs(italic), Shaping::Advanced);
136 buffer.shape_until_scroll(&mut fs, false);
137
138 let ox = origin.x as f32;
142 let oy = origin.y as f32;
143
144 let mut out = Vec::new();
145 for run in buffer.layout_runs() {
146 for glyph in run.glyphs.iter() {
147 let x_off = glyph.font_size * glyph.x_offset;
148 let y_off = glyph.font_size * glyph.y_offset;
149 let x = (glyph.x + x_off + ox).round();
150 let y = (glyph.y - y_off + oy).round();
151 let (cache_key, px, py) = CacheKey::new(
152 glyph.font_id,
153 glyph.glyph_id,
154 glyph.font_size,
155 (x, y),
156 glyph.cache_key_flags,
157 );
158 let image_ref = self.swash.get_image(&mut fs, cache_key);
159 if let Some(image) = image_ref.as_ref() {
160 if image.placement.width == 0 || image.placement.height == 0 {
161 continue;
162 }
163 let content = match image.content {
164 SwashContent::Mask => GlyphContent::Mask,
165 SwashContent::SubpixelMask => GlyphContent::SubpixelMask,
166 SwashContent::Color => GlyphContent::Color,
167 };
168 out.push(GlyphImage {
169 x: px + image.placement.left,
170 y: py - image.placement.top,
171 width: image.placement.width,
172 height: image.placement.height,
173 content,
174 data: image.data.clone(),
175 });
176 }
177 }
178 }
179 Ok(out)
180 }
181}