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