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::HashMap;
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<HashMap<Font, FontId>>,
41 font_metrics: RwLock<HashMap<FontId, FontMetrics>>,
42 raster_bounds: RwLock<HashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
43 wrapper_pool: Mutex<HashMap<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) -> Result<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 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) -> Result<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) -> Result<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) -> Result<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) -> Result<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) -> Result<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 ) -> Result<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 Ok(padding_top + ascent)
138 }
139
140 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> Result<T> {
141 let lock = self.font_metrics.upgradable_read();
142
143 if let Some(metrics) = lock.get(&font_id) {
144 Ok(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 Ok(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 line_start = line_end + 1; // Skip `\n` character.
294 font_runs.clear();
295 }
296
297 self.font_runs_pool.lock().push(font_runs);
298
299 Ok(lines)
300 }
301
302 pub fn start_frame(&self) {
303 self.line_layout_cache.start_frame()
304 }
305
306 pub fn line_wrapper(
307 self: &Arc<Self>,
308 font: Font,
309 font_size: Pixels,
310 ) -> Result<LineWrapperHandle> {
311 let lock = &mut self.wrapper_pool.lock();
312 let font_id = self.font_id(&font)?;
313 let wrappers = lock
314 .entry(FontIdWithSize { font_id, font_size })
315 .or_default();
316 let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
317 Ok(LineWrapper::new(
318 font_id,
319 font_size,
320 self.platform_text_system.clone(),
321 ))
322 })?;
323
324 Ok(LineWrapperHandle {
325 wrapper: Some(wrapper),
326 text_system: self.clone(),
327 })
328 }
329
330 pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
331 let raster_bounds = self.raster_bounds.upgradable_read();
332 if let Some(bounds) = raster_bounds.get(params) {
333 Ok(bounds.clone())
334 } else {
335 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
336 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
337 raster_bounds.insert(params.clone(), bounds);
338 Ok(bounds)
339 }
340 }
341
342 pub fn rasterize_glyph(
343 &self,
344 params: &RenderGlyphParams,
345 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
346 let raster_bounds = self.raster_bounds(params)?;
347 self.platform_text_system
348 .rasterize_glyph(params, raster_bounds)
349 }
350}
351
352#[derive(Hash, Eq, PartialEq)]
353struct FontIdWithSize {
354 font_id: FontId,
355 font_size: Pixels,
356}
357
358pub struct LineWrapperHandle {
359 wrapper: Option<LineWrapper>,
360 text_system: Arc<TextSystem>,
361}
362
363impl Drop for LineWrapperHandle {
364 fn drop(&mut self) {
365 let mut state = self.text_system.wrapper_pool.lock();
366 let wrapper = self.wrapper.take().unwrap();
367 state
368 .get_mut(&FontIdWithSize {
369 font_id: wrapper.font_id.clone(),
370 font_size: wrapper.font_size,
371 })
372 .unwrap()
373 .push(wrapper);
374 }
375}
376
377impl Deref for LineWrapperHandle {
378 type Target = LineWrapper;
379
380 fn deref(&self) -> &Self::Target {
381 self.wrapper.as_ref().unwrap()
382 }
383}
384
385impl DerefMut for LineWrapperHandle {
386 fn deref_mut(&mut self) -> &mut Self::Target {
387 self.wrapper.as_mut().unwrap()
388 }
389}
390
391/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
392/// with 400.0 as normal.
393#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
394pub struct FontWeight(pub f32);
395
396impl Default for FontWeight {
397 #[inline]
398 fn default() -> FontWeight {
399 FontWeight::NORMAL
400 }
401}
402
403impl Hash for FontWeight {
404 fn hash<H: Hasher>(&self, state: &mut H) {
405 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
406 }
407}
408
409impl Eq for FontWeight {}
410
411impl FontWeight {
412 /// Thin weight (100), the thinnest value.
413 pub const THIN: FontWeight = FontWeight(100.0);
414 /// Extra light weight (200).
415 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
416 /// Light weight (300).
417 pub const LIGHT: FontWeight = FontWeight(300.0);
418 /// Normal (400).
419 pub const NORMAL: FontWeight = FontWeight(400.0);
420 /// Medium weight (500, higher than normal).
421 pub const MEDIUM: FontWeight = FontWeight(500.0);
422 /// Semibold weight (600).
423 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
424 /// Bold weight (700).
425 pub const BOLD: FontWeight = FontWeight(700.0);
426 /// Extra-bold weight (800).
427 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
428 /// Black weight (900), the thickest value.
429 pub const BLACK: FontWeight = FontWeight(900.0);
430}
431
432/// Allows italic or oblique faces to be selected.
433#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
434pub enum FontStyle {
435 /// A face that is neither italic not obliqued.
436 Normal,
437 /// A form that is generally cursive in nature.
438 Italic,
439 /// A typically-sloped version of the regular face.
440 Oblique,
441}
442
443impl Default for FontStyle {
444 fn default() -> FontStyle {
445 FontStyle::Normal
446 }
447}
448
449impl Display for FontStyle {
450 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
451 Debug::fmt(self, f)
452 }
453}
454
455#[derive(Clone, Debug, PartialEq, Eq)]
456pub struct TextRun {
457 // number of utf8 bytes
458 pub len: usize,
459 pub font: Font,
460 pub color: Hsla,
461 pub background_color: Option<Hsla>,
462 pub underline: Option<UnderlineStyle>,
463}
464
465#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
466#[repr(C)]
467pub struct GlyphId(u32);
468
469impl From<GlyphId> for u32 {
470 fn from(value: GlyphId) -> Self {
471 value.0
472 }
473}
474
475impl From<u16> for GlyphId {
476 fn from(num: u16) -> Self {
477 GlyphId(num as u32)
478 }
479}
480
481impl From<u32> for GlyphId {
482 fn from(num: u32) -> Self {
483 GlyphId(num)
484 }
485}
486
487#[derive(Clone, Debug, PartialEq)]
488pub struct RenderGlyphParams {
489 pub(crate) font_id: FontId,
490 pub(crate) glyph_id: GlyphId,
491 pub(crate) font_size: Pixels,
492 pub(crate) subpixel_variant: Point<u8>,
493 pub(crate) scale_factor: f32,
494 pub(crate) is_emoji: bool,
495}
496
497impl Eq for RenderGlyphParams {}
498
499impl Hash for RenderGlyphParams {
500 fn hash<H: Hasher>(&self, state: &mut H) {
501 self.font_id.0.hash(state);
502 self.glyph_id.0.hash(state);
503 self.font_size.0.to_bits().hash(state);
504 self.subpixel_variant.hash(state);
505 self.scale_factor.to_bits().hash(state);
506 }
507}
508
509#[derive(Clone, Debug, PartialEq)]
510pub struct RenderEmojiParams {
511 pub(crate) font_id: FontId,
512 pub(crate) glyph_id: GlyphId,
513 pub(crate) font_size: Pixels,
514 pub(crate) scale_factor: f32,
515}
516
517impl Eq for RenderEmojiParams {}
518
519impl Hash for RenderEmojiParams {
520 fn hash<H: Hasher>(&self, state: &mut H) {
521 self.font_id.0.hash(state);
522 self.glyph_id.0.hash(state);
523 self.font_size.0.to_bits().hash(state);
524 self.scale_factor.to_bits().hash(state);
525 }
526}
527
528#[derive(Clone, Debug, Eq, PartialEq, Hash)]
529pub struct Font {
530 pub family: SharedString,
531 pub features: FontFeatures,
532 pub weight: FontWeight,
533 pub style: FontStyle,
534}
535
536pub fn font(family: impl Into<SharedString>) -> Font {
537 Font {
538 family: family.into(),
539 features: FontFeatures::default(),
540 weight: FontWeight::default(),
541 style: FontStyle::default(),
542 }
543}
544
545impl Font {
546 pub fn bold(mut self) -> Self {
547 self.weight = FontWeight::BOLD;
548 self
549 }
550}
551
552/// A struct for storing font metrics.
553/// It is used to define the measurements of a typeface.
554#[derive(Clone, Copy, Debug)]
555pub struct FontMetrics {
556 /// The number of font units that make up the "em square",
557 /// a scalable grid for determining the size of a typeface.
558 pub(crate) units_per_em: u32,
559
560 /// The vertical distance from the baseline of the font to the top of the glyph covers.
561 pub(crate) ascent: f32,
562
563 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
564 pub(crate) descent: f32,
565
566 /// The recommended additional space to add between lines of type.
567 pub(crate) line_gap: f32,
568
569 /// The suggested position of the underline.
570 pub(crate) underline_position: f32,
571
572 /// The suggested thickness of the underline.
573 pub(crate) underline_thickness: f32,
574
575 /// The height of a capital letter measured from the baseline of the font.
576 pub(crate) cap_height: f32,
577
578 /// The height of a lowercase x.
579 pub(crate) x_height: f32,
580
581 /// The outer limits of the area that the font covers.
582 pub(crate) bounding_box: Bounds<f32>,
583}
584
585impl FontMetrics {
586 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
587 pub fn ascent(&self, font_size: Pixels) -> Pixels {
588 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
589 }
590
591 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
592 pub fn descent(&self, font_size: Pixels) -> Pixels {
593 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
594 }
595
596 /// Returns the recommended additional space to add between lines of type in pixels.
597 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
598 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
599 }
600
601 /// Returns the suggested position of the underline in pixels.
602 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
603 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
604 }
605
606 /// Returns the suggested thickness of the underline in pixels.
607 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
608 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
609 }
610
611 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
612 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
613 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
614 }
615
616 /// Returns the height of a lowercase x in pixels.
617 pub fn x_height(&self, font_size: Pixels) -> Pixels {
618 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
619 }
620
621 /// Returns the outer limits of the area that the font covers in pixels.
622 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
623 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
624 }
625}