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 && last_run.underline == run.underline {
200 last_run.len += run.len as u32;
201 continue;
202 }
203 }
204 decoration_runs.push(DecorationRun {
205 len: run.len as u32,
206 color: run.color,
207 underline: run.underline.clone(),
208 });
209 }
210
211 let layout = self.layout_line(text.as_ref(), font_size, runs)?;
212
213 Ok(ShapedLine {
214 layout,
215 text,
216 decoration_runs,
217 })
218 }
219
220 pub fn shape_text(
221 &self,
222 text: &str, // todo!("pass a SharedString and preserve it when passed a single line?")
223 font_size: Pixels,
224 runs: &[TextRun],
225 wrap_width: Option<Pixels>,
226 ) -> Result<SmallVec<[WrappedLine; 1]>> {
227 let mut runs = runs.iter().cloned().peekable();
228 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
229
230 let mut lines = SmallVec::new();
231 let mut line_start = 0;
232 for line_text in text.split('\n') {
233 let line_text = SharedString::from(line_text.to_string());
234 let line_end = line_start + line_text.len();
235
236 let mut last_font: Option<Font> = None;
237 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
238 let mut run_start = line_start;
239 while run_start < line_end {
240 let Some(run) = runs.peek_mut() else {
241 break;
242 };
243
244 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
245
246 if last_font == Some(run.font.clone()) {
247 font_runs.last_mut().unwrap().len += run_len_within_line;
248 } else {
249 last_font = Some(run.font.clone());
250 font_runs.push(FontRun {
251 len: run_len_within_line,
252 font_id: self.platform_text_system.font_id(&run.font)?,
253 });
254 }
255
256 if decoration_runs.last().map_or(false, |last_run| {
257 last_run.color == run.color && last_run.underline == run.underline
258 }) {
259 decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
260 } else {
261 decoration_runs.push(DecorationRun {
262 len: run_len_within_line as u32,
263 color: run.color,
264 underline: run.underline.clone(),
265 });
266 }
267
268 if run_len_within_line == run.len {
269 runs.next();
270 } else {
271 // Preserve the remainder of the run for the next line
272 run.len -= run_len_within_line;
273 }
274 run_start += run_len_within_line;
275 }
276
277 let layout = self
278 .line_layout_cache
279 .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
280 lines.push(WrappedLine {
281 layout,
282 decoration_runs,
283 text: SharedString::from(line_text),
284 });
285
286 line_start = line_end + 1; // Skip `\n` character.
287 font_runs.clear();
288 }
289
290 self.font_runs_pool.lock().push(font_runs);
291
292 Ok(lines)
293 }
294
295 pub fn start_frame(&self) {
296 self.line_layout_cache.start_frame()
297 }
298
299 pub fn line_wrapper(
300 self: &Arc<Self>,
301 font: Font,
302 font_size: Pixels,
303 ) -> Result<LineWrapperHandle> {
304 let lock = &mut self.wrapper_pool.lock();
305 let font_id = self.font_id(&font)?;
306 let wrappers = lock
307 .entry(FontIdWithSize { font_id, font_size })
308 .or_default();
309 let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
310 Ok(LineWrapper::new(
311 font_id,
312 font_size,
313 self.platform_text_system.clone(),
314 ))
315 })?;
316
317 Ok(LineWrapperHandle {
318 wrapper: Some(wrapper),
319 text_system: self.clone(),
320 })
321 }
322
323 pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
324 let raster_bounds = self.raster_bounds.upgradable_read();
325 if let Some(bounds) = raster_bounds.get(params) {
326 Ok(bounds.clone())
327 } else {
328 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
329 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
330 raster_bounds.insert(params.clone(), bounds);
331 Ok(bounds)
332 }
333 }
334
335 pub fn rasterize_glyph(
336 &self,
337 params: &RenderGlyphParams,
338 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
339 let raster_bounds = self.raster_bounds(params)?;
340 self.platform_text_system
341 .rasterize_glyph(params, raster_bounds)
342 }
343}
344
345#[derive(Hash, Eq, PartialEq)]
346struct FontIdWithSize {
347 font_id: FontId,
348 font_size: Pixels,
349}
350
351pub struct LineWrapperHandle {
352 wrapper: Option<LineWrapper>,
353 text_system: Arc<TextSystem>,
354}
355
356impl Drop for LineWrapperHandle {
357 fn drop(&mut self) {
358 let mut state = self.text_system.wrapper_pool.lock();
359 let wrapper = self.wrapper.take().unwrap();
360 state
361 .get_mut(&FontIdWithSize {
362 font_id: wrapper.font_id.clone(),
363 font_size: wrapper.font_size,
364 })
365 .unwrap()
366 .push(wrapper);
367 }
368}
369
370impl Deref for LineWrapperHandle {
371 type Target = LineWrapper;
372
373 fn deref(&self) -> &Self::Target {
374 self.wrapper.as_ref().unwrap()
375 }
376}
377
378impl DerefMut for LineWrapperHandle {
379 fn deref_mut(&mut self) -> &mut Self::Target {
380 self.wrapper.as_mut().unwrap()
381 }
382}
383
384/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
385/// with 400.0 as normal.
386#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
387pub struct FontWeight(pub f32);
388
389impl Default for FontWeight {
390 #[inline]
391 fn default() -> FontWeight {
392 FontWeight::NORMAL
393 }
394}
395
396impl Hash for FontWeight {
397 fn hash<H: Hasher>(&self, state: &mut H) {
398 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
399 }
400}
401
402impl Eq for FontWeight {}
403
404impl FontWeight {
405 /// Thin weight (100), the thinnest value.
406 pub const THIN: FontWeight = FontWeight(100.0);
407 /// Extra light weight (200).
408 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
409 /// Light weight (300).
410 pub const LIGHT: FontWeight = FontWeight(300.0);
411 /// Normal (400).
412 pub const NORMAL: FontWeight = FontWeight(400.0);
413 /// Medium weight (500, higher than normal).
414 pub const MEDIUM: FontWeight = FontWeight(500.0);
415 /// Semibold weight (600).
416 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
417 /// Bold weight (700).
418 pub const BOLD: FontWeight = FontWeight(700.0);
419 /// Extra-bold weight (800).
420 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
421 /// Black weight (900), the thickest value.
422 pub const BLACK: FontWeight = FontWeight(900.0);
423}
424
425/// Allows italic or oblique faces to be selected.
426#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
427pub enum FontStyle {
428 /// A face that is neither italic not obliqued.
429 Normal,
430 /// A form that is generally cursive in nature.
431 Italic,
432 /// A typically-sloped version of the regular face.
433 Oblique,
434}
435
436impl Default for FontStyle {
437 fn default() -> FontStyle {
438 FontStyle::Normal
439 }
440}
441
442impl Display for FontStyle {
443 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
444 Debug::fmt(self, f)
445 }
446}
447
448#[derive(Clone, Debug, PartialEq, Eq)]
449pub struct TextRun {
450 // number of utf8 bytes
451 pub len: usize,
452 pub font: Font,
453 pub color: Hsla,
454 pub background_color: Option<Hsla>,
455 pub underline: Option<UnderlineStyle>,
456}
457
458#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
459#[repr(C)]
460pub struct GlyphId(u32);
461
462impl From<GlyphId> for u32 {
463 fn from(value: GlyphId) -> Self {
464 value.0
465 }
466}
467
468impl From<u16> for GlyphId {
469 fn from(num: u16) -> Self {
470 GlyphId(num as u32)
471 }
472}
473
474impl From<u32> for GlyphId {
475 fn from(num: u32) -> Self {
476 GlyphId(num)
477 }
478}
479
480#[derive(Clone, Debug, PartialEq)]
481pub struct RenderGlyphParams {
482 pub(crate) font_id: FontId,
483 pub(crate) glyph_id: GlyphId,
484 pub(crate) font_size: Pixels,
485 pub(crate) subpixel_variant: Point<u8>,
486 pub(crate) scale_factor: f32,
487 pub(crate) is_emoji: bool,
488}
489
490impl Eq for RenderGlyphParams {}
491
492impl Hash for RenderGlyphParams {
493 fn hash<H: Hasher>(&self, state: &mut H) {
494 self.font_id.0.hash(state);
495 self.glyph_id.0.hash(state);
496 self.font_size.0.to_bits().hash(state);
497 self.subpixel_variant.hash(state);
498 self.scale_factor.to_bits().hash(state);
499 }
500}
501
502#[derive(Clone, Debug, PartialEq)]
503pub struct RenderEmojiParams {
504 pub(crate) font_id: FontId,
505 pub(crate) glyph_id: GlyphId,
506 pub(crate) font_size: Pixels,
507 pub(crate) scale_factor: f32,
508}
509
510impl Eq for RenderEmojiParams {}
511
512impl Hash for RenderEmojiParams {
513 fn hash<H: Hasher>(&self, state: &mut H) {
514 self.font_id.0.hash(state);
515 self.glyph_id.0.hash(state);
516 self.font_size.0.to_bits().hash(state);
517 self.scale_factor.to_bits().hash(state);
518 }
519}
520
521#[derive(Clone, Debug, Eq, PartialEq, Hash)]
522pub struct Font {
523 pub family: SharedString,
524 pub features: FontFeatures,
525 pub weight: FontWeight,
526 pub style: FontStyle,
527}
528
529pub fn font(family: impl Into<SharedString>) -> Font {
530 Font {
531 family: family.into(),
532 features: FontFeatures::default(),
533 weight: FontWeight::default(),
534 style: FontStyle::default(),
535 }
536}
537
538impl Font {
539 pub fn bold(mut self) -> Self {
540 self.weight = FontWeight::BOLD;
541 self
542 }
543}
544
545/// A struct for storing font metrics.
546/// It is used to define the measurements of a typeface.
547#[derive(Clone, Copy, Debug)]
548pub struct FontMetrics {
549 /// The number of font units that make up the "em square",
550 /// a scalable grid for determining the size of a typeface.
551 pub(crate) units_per_em: u32,
552
553 /// The vertical distance from the baseline of the font to the top of the glyph covers.
554 pub(crate) ascent: f32,
555
556 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
557 pub(crate) descent: f32,
558
559 /// The recommended additional space to add between lines of type.
560 pub(crate) line_gap: f32,
561
562 /// The suggested position of the underline.
563 pub(crate) underline_position: f32,
564
565 /// The suggested thickness of the underline.
566 pub(crate) underline_thickness: f32,
567
568 /// The height of a capital letter measured from the baseline of the font.
569 pub(crate) cap_height: f32,
570
571 /// The height of a lowercase x.
572 pub(crate) x_height: f32,
573
574 /// The outer limits of the area that the font covers.
575 pub(crate) bounding_box: Bounds<f32>,
576}
577
578impl FontMetrics {
579 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
580 pub fn ascent(&self, font_size: Pixels) -> Pixels {
581 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
582 }
583
584 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
585 pub fn descent(&self, font_size: Pixels) -> Pixels {
586 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
587 }
588
589 /// Returns the recommended additional space to add between lines of type in pixels.
590 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
591 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
592 }
593
594 /// Returns the suggested position of the underline in pixels.
595 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
596 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
597 }
598
599 /// Returns the suggested thickness of the underline in pixels.
600 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
601 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
602 }
603
604 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
605 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
606 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
607 }
608
609 /// Returns the height of a lowercase x in pixels.
610 pub fn x_height(&self, font_size: Pixels) -> Pixels {
611 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
612 }
613
614 /// Returns the outer limits of the area that the font covers in pixels.
615 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
616 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
617 }
618}