1mod font_features;
2mod line;
3mod line_wrapper;
4mod text_layout_cache;
5
6use anyhow::anyhow;
7use bytemuck::{Pod, Zeroable};
8pub use font_features::*;
9pub use line::*;
10use line_wrapper::*;
11pub use text_layout_cache::*;
12
13use crate::{
14 px, Bounds, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size, UnderlineStyle,
15};
16use collections::HashMap;
17use core::fmt;
18use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
19use std::{
20 fmt::{Debug, Display, Formatter},
21 hash::{Hash, Hasher},
22 ops::{Deref, DerefMut},
23 sync::Arc,
24};
25
26#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug, Zeroable, Pod)]
27#[repr(C)]
28pub struct FontId(pub usize);
29
30#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
31pub struct FontFamilyId(pub usize);
32
33pub struct TextSystem {
34 text_layout_cache: Arc<TextLayoutCache>,
35 platform_text_system: Arc<dyn PlatformTextSystem>,
36 font_ids_by_font: RwLock<HashMap<Font, FontId>>,
37 fonts_by_font_id: RwLock<HashMap<FontId, Font>>,
38 font_metrics: RwLock<HashMap<Font, FontMetrics>>,
39 wrapper_pool: Mutex<HashMap<FontIdWithSize, Vec<LineWrapper>>>,
40 font_runs_pool: Mutex<Vec<Vec<(usize, FontId)>>>,
41}
42
43impl TextSystem {
44 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
45 TextSystem {
46 text_layout_cache: Arc::new(TextLayoutCache::new(platform_text_system.clone())),
47 platform_text_system,
48 font_metrics: RwLock::new(HashMap::default()),
49 font_ids_by_font: RwLock::new(HashMap::default()),
50 fonts_by_font_id: RwLock::new(HashMap::default()),
51 wrapper_pool: Mutex::new(HashMap::default()),
52 font_runs_pool: Default::default(),
53 }
54 }
55
56 pub fn font_id(&self, font: &Font) -> Result<FontId> {
57 let font_id = self.font_ids_by_font.read().get(font).copied();
58 if let Some(font_id) = font_id {
59 Ok(font_id)
60 } else {
61 let font_id = self.platform_text_system.font_id(font)?;
62 self.font_ids_by_font.write().insert(font.clone(), font_id);
63 self.fonts_by_font_id.write().insert(font_id, font.clone());
64 Ok(font_id)
65 }
66 }
67
68 pub fn with_font<T>(&self, font_id: FontId, f: impl FnOnce(&Self, &Font) -> T) -> Result<T> {
69 self.fonts_by_font_id
70 .read()
71 .get(&font_id)
72 .ok_or_else(|| anyhow!("font not found"))
73 .map(|font| f(self, font))
74 }
75
76 pub fn bounding_box(&self, font: &Font, font_size: Pixels) -> Result<Bounds<Pixels>> {
77 self.read_metrics(&font, |metrics| metrics.bounding_box(font_size))
78 }
79
80 pub fn typographic_bounds(
81 &self,
82 font: &Font,
83 font_size: Pixels,
84 character: char,
85 ) -> Result<Bounds<Pixels>> {
86 let font_id = self.font_id(font)?;
87 let glyph_id = self
88 .platform_text_system
89 .glyph_for_char(font_id, character)
90 .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
91 let bounds = self
92 .platform_text_system
93 .typographic_bounds(font_id, glyph_id)?;
94 self.read_metrics(font, |metrics| {
95 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
96 })
97 }
98
99 pub fn advance(&self, font: &Font, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
100 let font_id = self.font_id(font)?;
101 let glyph_id = self
102 .platform_text_system
103 .glyph_for_char(font_id, ch)
104 .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
105 let result =
106 self.platform_text_system.advance(font_id, glyph_id)? / self.units_per_em(font)? as f32;
107
108 Ok(result * font_size)
109 }
110
111 pub fn units_per_em(&self, font: &Font) -> Result<u32> {
112 self.read_metrics(font, |metrics| metrics.units_per_em as u32)
113 }
114
115 pub fn cap_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
116 self.read_metrics(font, |metrics| metrics.cap_height(font_size))
117 }
118
119 pub fn x_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
120 self.read_metrics(font, |metrics| metrics.x_height(font_size))
121 }
122
123 pub fn ascent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
124 self.read_metrics(font, |metrics| metrics.ascent(font_size))
125 }
126
127 pub fn descent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
128 self.read_metrics(font, |metrics| metrics.descent(font_size))
129 }
130
131 pub fn baseline_offset(
132 &self,
133 font: &Font,
134 font_size: Pixels,
135 line_height: Pixels,
136 ) -> Result<Pixels> {
137 let ascent = self.ascent(font, font_size)?;
138 let descent = self.descent(font, font_size)?;
139 let padding_top = (line_height - ascent - descent) / 2.;
140 Ok(padding_top + ascent)
141 }
142
143 fn read_metrics<T>(&self, font: &Font, read: impl FnOnce(&FontMetrics) -> T) -> Result<T> {
144 let lock = self.font_metrics.upgradable_read();
145
146 if let Some(metrics) = lock.get(font) {
147 Ok(read(metrics))
148 } else {
149 let font_id = self.platform_text_system.font_id(&font)?;
150 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
151 let metrics = lock
152 .entry(font.clone())
153 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
154 Ok(read(metrics))
155 }
156 }
157
158 pub fn layout_line(
159 &self,
160 text: &str,
161 font_size: Pixels,
162 runs: &[(usize, RunStyle)],
163 ) -> Result<Line> {
164 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
165
166 let mut last_font: Option<&Font> = None;
167 for (len, style) in runs {
168 if let Some(last_font) = last_font.as_ref() {
169 if **last_font == style.font {
170 font_runs.last_mut().unwrap().0 += len;
171 continue;
172 }
173 }
174 last_font = Some(&style.font);
175 font_runs.push((*len, self.font_id(&style.font)?));
176 }
177
178 let layout = self
179 .text_layout_cache
180 .layout_line(text, font_size, &font_runs);
181
182 font_runs.clear();
183 self.font_runs_pool.lock().push(font_runs);
184
185 Ok(Line::new(layout.clone(), runs))
186 }
187
188 pub fn finish_frame(&self) {
189 self.text_layout_cache.finish_frame()
190 }
191
192 pub fn line_wrapper(
193 self: &Arc<Self>,
194 font: Font,
195 font_size: Pixels,
196 ) -> Result<LineWrapperHandle> {
197 let lock = &mut self.wrapper_pool.lock();
198 let font_id = self.font_id(&font)?;
199 let wrappers = lock
200 .entry(FontIdWithSize { font_id, font_size })
201 .or_default();
202 let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
203 Ok(LineWrapper::new(
204 font_id,
205 font_size,
206 self.platform_text_system.clone(),
207 ))
208 })?;
209
210 Ok(LineWrapperHandle {
211 wrapper: Some(wrapper),
212 text_system: self.clone(),
213 })
214 }
215}
216
217#[derive(Hash, Eq, PartialEq)]
218struct FontIdWithSize {
219 font_id: FontId,
220 font_size: Pixels,
221}
222
223pub struct LineWrapperHandle {
224 wrapper: Option<LineWrapper>,
225 text_system: Arc<TextSystem>,
226}
227
228impl Drop for LineWrapperHandle {
229 fn drop(&mut self) {
230 let mut state = self.text_system.wrapper_pool.lock();
231 let wrapper = self.wrapper.take().unwrap();
232 state
233 .get_mut(&FontIdWithSize {
234 font_id: wrapper.font_id.clone(),
235 font_size: wrapper.font_size,
236 })
237 .unwrap()
238 .push(wrapper);
239 }
240}
241
242impl Deref for LineWrapperHandle {
243 type Target = LineWrapper;
244
245 fn deref(&self) -> &Self::Target {
246 self.wrapper.as_ref().unwrap()
247 }
248}
249
250impl DerefMut for LineWrapperHandle {
251 fn deref_mut(&mut self) -> &mut Self::Target {
252 self.wrapper.as_mut().unwrap()
253 }
254}
255
256/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
257/// with 400.0 as normal.
258#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
259pub struct FontWeight(pub f32);
260
261impl Default for FontWeight {
262 #[inline]
263 fn default() -> FontWeight {
264 FontWeight::NORMAL
265 }
266}
267
268impl Hash for FontWeight {
269 fn hash<H: Hasher>(&self, state: &mut H) {
270 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
271 }
272}
273
274impl Eq for FontWeight {}
275
276impl FontWeight {
277 /// Thin weight (100), the thinnest value.
278 pub const THIN: FontWeight = FontWeight(100.0);
279 /// Extra light weight (200).
280 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
281 /// Light weight (300).
282 pub const LIGHT: FontWeight = FontWeight(300.0);
283 /// Normal (400).
284 pub const NORMAL: FontWeight = FontWeight(400.0);
285 /// Medium weight (500, higher than normal).
286 pub const MEDIUM: FontWeight = FontWeight(500.0);
287 /// Semibold weight (600).
288 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
289 /// Bold weight (700).
290 pub const BOLD: FontWeight = FontWeight(700.0);
291 /// Extra-bold weight (800).
292 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
293 /// Black weight (900), the thickest value.
294 pub const BLACK: FontWeight = FontWeight(900.0);
295}
296
297/// Allows italic or oblique faces to be selected.
298#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
299pub enum FontStyle {
300 /// A face that is neither italic not obliqued.
301 Normal,
302 /// A form that is generally cursive in nature.
303 Italic,
304 /// A typically-sloped version of the regular face.
305 Oblique,
306}
307
308impl Default for FontStyle {
309 fn default() -> FontStyle {
310 FontStyle::Normal
311 }
312}
313
314impl Display for FontStyle {
315 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
316 Debug::fmt(self, f)
317 }
318}
319
320#[derive(Clone, Debug, PartialEq, Eq)]
321pub struct RunStyle {
322 pub font: Font,
323 pub color: Hsla,
324 pub underline: Option<UnderlineStyle>,
325}
326
327#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Zeroable, Pod)]
328#[repr(C)]
329pub struct GlyphId(u32);
330
331impl From<GlyphId> for u32 {
332 fn from(value: GlyphId) -> Self {
333 value.0
334 }
335}
336
337impl From<u16> for GlyphId {
338 fn from(num: u16) -> Self {
339 GlyphId(num as u32)
340 }
341}
342
343impl From<u32> for GlyphId {
344 fn from(num: u32) -> Self {
345 GlyphId(num)
346 }
347}
348
349#[derive(Default, Debug)]
350pub struct ShapedLine {
351 pub font_size: Pixels,
352 pub width: Pixels,
353 pub ascent: Pixels,
354 pub descent: Pixels,
355 pub runs: Vec<ShapedRun>,
356 pub len: usize,
357}
358
359#[derive(Debug)]
360pub struct ShapedRun {
361 pub font_id: FontId,
362 pub glyphs: Vec<ShapedGlyph>,
363}
364
365#[derive(Clone, Debug)]
366pub struct ShapedGlyph {
367 pub id: GlyphId,
368 pub position: Point<Pixels>,
369 pub index: usize,
370 pub is_emoji: bool,
371}
372
373#[derive(Clone, Debug, Eq, PartialEq, Hash)]
374pub struct RasterizedGlyphId {
375 font_id: FontId,
376 glyph_id: GlyphId,
377 font_size: Pixels,
378}
379
380#[derive(Clone, Debug, Eq, PartialEq, Hash)]
381pub struct Font {
382 pub family: SharedString,
383 pub features: FontFeatures,
384 pub weight: FontWeight,
385 pub style: FontStyle,
386}
387
388pub fn font(family: impl Into<SharedString>) -> Font {
389 Font {
390 family: family.into(),
391 features: FontFeatures::default(),
392 weight: FontWeight::default(),
393 style: FontStyle::default(),
394 }
395}
396
397impl Font {
398 pub fn bold(mut self) -> Self {
399 self.weight = FontWeight::BOLD;
400 self
401 }
402}
403
404/// A struct for storing font metrics.
405/// It is used to define the measurements of a typeface.
406#[derive(Clone, Copy, Debug)]
407pub struct FontMetrics {
408 /// The number of font units that make up the "em square",
409 /// a scalable grid for determining the size of a typeface.
410 pub(crate) units_per_em: u32,
411
412 /// The vertical distance from the baseline of the font to the top of the glyph covers.
413 pub(crate) ascent: f32,
414
415 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
416 pub(crate) descent: f32,
417
418 /// The recommended additional space to add between lines of type.
419 pub(crate) line_gap: f32,
420
421 /// The suggested position of the underline.
422 pub(crate) underline_position: f32,
423
424 /// The suggested thickness of the underline.
425 pub(crate) underline_thickness: f32,
426
427 /// The height of a capital letter measured from the baseline of the font.
428 pub(crate) cap_height: f32,
429
430 /// The height of a lowercase x.
431 pub(crate) x_height: f32,
432
433 /// The outer limits of the area that the font covers.
434 pub(crate) bounding_box: Bounds<f32>,
435}
436
437impl FontMetrics {
438 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
439 pub fn ascent(&self, font_size: Pixels) -> Pixels {
440 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
441 }
442
443 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
444 pub fn descent(&self, font_size: Pixels) -> Pixels {
445 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
446 }
447
448 /// Returns the recommended additional space to add between lines of type in pixels.
449 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
450 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
451 }
452
453 /// Returns the suggested position of the underline in pixels.
454 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
455 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
456 }
457
458 /// Returns the suggested thickness of the underline in pixels.
459 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
460 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
461 }
462
463 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
464 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
465 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
466 }
467
468 /// Returns the height of a lowercase x in pixels.
469 pub fn x_height(&self, font_size: Pixels) -> Pixels {
470 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
471 }
472
473 /// Returns the outer limits of the area that the font covers in pixels.
474 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
475 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
476 }
477}