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