1mod font_features;
2mod line_wrapper;
3mod text_layout_cache;
4
5use anyhow::anyhow;
6pub use font_features::*;
7use line_wrapper::*;
8pub use text_layout_cache::*;
9
10use crate::{
11 px, Bounds, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size, UnderlineStyle,
12};
13use collections::HashMap;
14use core::fmt;
15use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
16use std::{
17 fmt::{Debug, Display, Formatter},
18 hash::{Hash, Hasher},
19 ops::{Deref, DerefMut},
20 sync::Arc,
21};
22
23#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
24pub struct FontId(pub usize);
25
26#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
27pub struct FontFamilyId(pub usize);
28
29pub struct TextSystem {
30 text_layout_cache: Arc<TextLayoutCache>,
31 platform_text_system: Arc<dyn PlatformTextSystem>,
32 font_ids_by_font: RwLock<HashMap<Font, FontId>>,
33 fonts_by_font_id: RwLock<HashMap<FontId, Font>>,
34 font_metrics: RwLock<HashMap<Font, FontMetrics>>,
35 wrapper_pool: Mutex<HashMap<FontIdWithSize, Vec<LineWrapper>>>,
36 font_runs_pool: Mutex<Vec<Vec<(usize, FontId)>>>,
37}
38
39impl TextSystem {
40 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
41 TextSystem {
42 text_layout_cache: Arc::new(TextLayoutCache::new(platform_text_system.clone())),
43 platform_text_system,
44 font_metrics: RwLock::new(HashMap::default()),
45 font_ids_by_font: RwLock::new(HashMap::default()),
46 fonts_by_font_id: RwLock::new(HashMap::default()),
47 wrapper_pool: Mutex::new(HashMap::default()),
48 font_runs_pool: Default::default(),
49 }
50 }
51
52 pub fn font_id(&self, font: &Font) -> Result<FontId> {
53 let font_id = self.font_ids_by_font.read().get(font).copied();
54
55 if let Some(font_id) = font_id {
56 Ok(font_id)
57 } else {
58 let font_id = self.platform_text_system.font_id(font)?;
59 self.font_ids_by_font.write().insert(font.clone(), font_id);
60 self.fonts_by_font_id.write().insert(font_id, font.clone());
61 Ok(font_id)
62 }
63 }
64
65 pub fn with_font<T>(&self, font_id: FontId, f: impl FnOnce(&Self, &Font) -> T) -> Result<T> {
66 self.fonts_by_font_id
67 .read()
68 .get(&font_id)
69 .ok_or_else(|| anyhow!("font not found"))
70 .map(|font| f(self, font))
71 }
72
73 pub fn bounding_box(&self, font: &Font, font_size: Pixels) -> Result<Bounds<Pixels>> {
74 self.read_metrics(&font, |metrics| metrics.bounding_box(font_size))
75 }
76
77 pub fn typographic_bounds(
78 &self,
79 font: &Font,
80 font_size: Pixels,
81 character: char,
82 ) -> Result<Bounds<Pixels>> {
83 let font_id = self.font_id(font)?;
84 let glyph_id = self
85 .platform_text_system
86 .glyph_for_char(font_id, character)
87 .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
88 let bounds = self
89 .platform_text_system
90 .typographic_bounds(font_id, glyph_id)?;
91 self.read_metrics(font, |metrics| {
92 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
93 })
94 }
95
96 pub fn advance(&self, font: &Font, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
97 let font_id = self.font_id(font)?;
98 let glyph_id = self
99 .platform_text_system
100 .glyph_for_char(font_id, ch)
101 .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
102 let result =
103 self.platform_text_system.advance(font_id, glyph_id)? / self.units_per_em(font)? as f32;
104
105 Ok(result * font_size)
106 }
107
108 pub fn units_per_em(&self, font: &Font) -> Result<u32> {
109 self.read_metrics(font, |metrics| metrics.units_per_em as u32)
110 }
111
112 pub fn cap_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
113 self.read_metrics(font, |metrics| metrics.cap_height(font_size))
114 }
115
116 pub fn x_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
117 self.read_metrics(font, |metrics| metrics.x_height(font_size))
118 }
119
120 pub fn ascent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
121 self.read_metrics(font, |metrics| metrics.ascent(font_size))
122 }
123
124 pub fn descent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
125 self.read_metrics(font, |metrics| metrics.descent(font_size))
126 }
127
128 pub fn baseline_offset(
129 &self,
130 font: &Font,
131 font_size: Pixels,
132 line_height: Pixels,
133 ) -> Result<Pixels> {
134 let ascent = self.ascent(font, font_size)?;
135 let descent = self.descent(font, font_size)?;
136 let padding_top = (line_height - ascent - descent) / 2.;
137 Ok(padding_top + ascent)
138 }
139
140 fn read_metrics<T>(&self, font: &Font, read: impl FnOnce(&FontMetrics) -> T) -> Result<T> {
141 let lock = self.font_metrics.upgradable_read();
142
143 if let Some(metrics) = lock.get(font) {
144 Ok(read(metrics))
145 } else {
146 let font_id = self.platform_text_system.font_id(&font)?;
147 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
148 let metrics = lock
149 .entry(font.clone())
150 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
151 Ok(read(metrics))
152 }
153 }
154
155 pub fn layout_line(
156 &self,
157 text: &str,
158 font_size: Pixels,
159 runs: &[(usize, RunStyle)],
160 ) -> Result<Line> {
161 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
162
163 dbg!("got font runs from pool");
164 let mut last_font: Option<&Font> = None;
165 for (len, style) in runs {
166 dbg!(len);
167 if let Some(last_font) = last_font.as_ref() {
168 dbg!("a");
169 if **last_font == style.font {
170 dbg!("b");
171 font_runs.last_mut().unwrap().0 += len;
172 dbg!("c");
173 continue;
174 }
175 dbg!("d");
176 }
177 dbg!("e");
178 last_font = Some(&style.font);
179 dbg!("f");
180 font_runs.push((*len, self.font_id(&style.font)?));
181 dbg!("g");
182 }
183
184 dbg!("built font runs");
185
186 let layout = self
187 .text_layout_cache
188 .layout_line(text, font_size, &font_runs);
189
190 font_runs.clear();
191 self.font_runs_pool.lock().push(font_runs);
192
193 Ok(Line::new(layout.clone(), runs))
194 }
195
196 pub fn finish_frame(&self) {
197 self.text_layout_cache.finish_frame()
198 }
199
200 pub fn line_wrapper(
201 self: &Arc<Self>,
202 font: Font,
203 font_size: Pixels,
204 ) -> Result<LineWrapperHandle> {
205 let lock = &mut self.wrapper_pool.lock();
206 let font_id = self.font_id(&font)?;
207 let wrappers = lock
208 .entry(FontIdWithSize { font_id, font_size })
209 .or_default();
210 let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
211 Ok(LineWrapper::new(
212 font_id,
213 font_size,
214 self.platform_text_system.clone(),
215 ))
216 })?;
217
218 Ok(LineWrapperHandle {
219 wrapper: Some(wrapper),
220 text_system: self.clone(),
221 })
222 }
223}
224
225#[derive(Hash, Eq, PartialEq)]
226struct FontIdWithSize {
227 font_id: FontId,
228 font_size: Pixels,
229}
230
231pub struct LineWrapperHandle {
232 wrapper: Option<LineWrapper>,
233 text_system: Arc<TextSystem>,
234}
235
236impl Drop for LineWrapperHandle {
237 fn drop(&mut self) {
238 let mut state = self.text_system.wrapper_pool.lock();
239 let wrapper = self.wrapper.take().unwrap();
240 state
241 .get_mut(&FontIdWithSize {
242 font_id: wrapper.font_id.clone(),
243 font_size: wrapper.font_size,
244 })
245 .unwrap()
246 .push(wrapper);
247 }
248}
249
250impl Deref for LineWrapperHandle {
251 type Target = LineWrapper;
252
253 fn deref(&self) -> &Self::Target {
254 self.wrapper.as_ref().unwrap()
255 }
256}
257
258impl DerefMut for LineWrapperHandle {
259 fn deref_mut(&mut self) -> &mut Self::Target {
260 self.wrapper.as_mut().unwrap()
261 }
262}
263
264/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
265/// with 400.0 as normal.
266#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
267pub struct FontWeight(pub f32);
268
269impl Default for FontWeight {
270 #[inline]
271 fn default() -> FontWeight {
272 FontWeight::NORMAL
273 }
274}
275
276impl Hash for FontWeight {
277 fn hash<H: Hasher>(&self, state: &mut H) {
278 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
279 }
280}
281
282impl Eq for FontWeight {}
283
284impl FontWeight {
285 /// Thin weight (100), the thinnest value.
286 pub const THIN: FontWeight = FontWeight(100.0);
287 /// Extra light weight (200).
288 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
289 /// Light weight (300).
290 pub const LIGHT: FontWeight = FontWeight(300.0);
291 /// Normal (400).
292 pub const NORMAL: FontWeight = FontWeight(400.0);
293 /// Medium weight (500, higher than normal).
294 pub const MEDIUM: FontWeight = FontWeight(500.0);
295 /// Semibold weight (600).
296 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
297 /// Bold weight (700).
298 pub const BOLD: FontWeight = FontWeight(700.0);
299 /// Extra-bold weight (800).
300 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
301 /// Black weight (900), the thickest value.
302 pub const BLACK: FontWeight = FontWeight(900.0);
303}
304
305/// Allows italic or oblique faces to be selected.
306#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
307pub enum FontStyle {
308 /// A face that is neither italic not obliqued.
309 Normal,
310 /// A form that is generally cursive in nature.
311 Italic,
312 /// A typically-sloped version of the regular face.
313 Oblique,
314}
315
316impl Default for FontStyle {
317 fn default() -> FontStyle {
318 FontStyle::Normal
319 }
320}
321
322impl Display for FontStyle {
323 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
324 Debug::fmt(self, f)
325 }
326}
327
328#[derive(Clone, Debug, PartialEq, Eq)]
329pub struct RunStyle {
330 pub font: Font,
331 pub color: Hsla,
332 pub underline: Option<UnderlineStyle>,
333}
334
335#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
336pub struct GlyphId(u32);
337
338impl From<GlyphId> for u32 {
339 fn from(value: GlyphId) -> Self {
340 value.0
341 }
342}
343
344impl From<u16> for GlyphId {
345 fn from(num: u16) -> Self {
346 GlyphId(num as u32)
347 }
348}
349
350impl From<u32> for GlyphId {
351 fn from(num: u32) -> Self {
352 GlyphId(num)
353 }
354}
355
356#[derive(Clone, Debug)]
357pub struct Glyph {
358 pub id: GlyphId,
359 pub position: Point<Pixels>,
360 pub index: usize,
361 pub is_emoji: bool,
362}
363
364#[derive(Default, Debug)]
365pub struct LineLayout {
366 pub font_size: Pixels,
367 pub width: Pixels,
368 pub ascent: Pixels,
369 pub descent: Pixels,
370 pub runs: Vec<Run>,
371 pub len: usize,
372}
373
374#[derive(Debug)]
375pub struct Run {
376 pub font_id: FontId,
377 pub glyphs: Vec<Glyph>,
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}