1mod font_fallbacks;
2mod font_features;
3mod line;
4mod line_layout;
5mod line_wrapper;
6
7pub use font_fallbacks::*;
8pub use font_features::*;
9pub use line::*;
10pub use line_layout::*;
11pub use line_wrapper::*;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
17 StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
18};
19use anyhow::Context as _;
20use collections::{FxHashMap, FxHashSet};
21use core::fmt;
22use derive_more::{Add, Deref, FromStr, Sub};
23use itertools::Itertools;
24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
25use smallvec::{SmallVec, smallvec};
26use std::{
27 borrow::Cow,
28 cell::Cell,
29 cmp,
30 collections::VecDeque,
31 fmt::{Debug, Display, Formatter},
32 hash::{Hash, Hasher},
33 ops::{Deref, DerefMut, Range},
34 sync::{
35 Arc,
36 atomic::{AtomicUsize, Ordering},
37 },
38};
39
40#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
42#[repr(C)]
43pub struct FontId(pub usize);
44
45#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
47pub struct FontFamilyId(pub usize);
48
49pub const SUBPIXEL_VARIANTS_X: u8 = 4;
51
52pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
54
55const UNDERLINE_DESCENT_OFFSET_FACTOR: f32 = 0.618;
57
58pub fn underline_y_offset(line_height: Pixels, ascent: Pixels, descent: Pixels) -> Pixels {
60 let padding_top = (line_height - ascent - descent) / 2.;
61 padding_top + ascent + descent * UNDERLINE_DESCENT_OFFSET_FACTOR
62}
63
64const MAX_REPORTED_MISSING_GLYPHS: usize = 1024;
65
66#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
68pub enum FallbackFontClass {
69 Proportional,
71 Monospace,
73}
74
75#[derive(Clone, Debug, Eq, Hash, PartialEq)]
77pub struct MissingGlyph {
78 grapheme: SharedString,
79 font_class: FallbackFontClass,
80}
81
82impl MissingGlyph {
83 pub fn new(grapheme: SharedString, font_class: FallbackFontClass) -> Self {
85 Self {
86 grapheme,
87 font_class,
88 }
89 }
90
91 pub fn grapheme(&self) -> &str {
93 &self.grapheme
94 }
95
96 pub fn font_class(&self) -> FallbackFontClass {
98 self.font_class
99 }
100}
101
102pub trait MissingGlyphSink: Send + Sync {
104 fn report(&self, missing_glyphs: Vec<MissingGlyph>);
106}
107
108#[derive(Default)]
109struct MissingGlyphState {
110 reported: FxHashSet<MissingGlyph>,
111 reported_order: VecDeque<MissingGlyph>,
112 generation: usize,
113}
114
115impl MissingGlyphState {
116 fn reset(&mut self, generation: usize) {
117 self.reported.clear();
118 self.reported_order.clear();
119 self.generation = generation;
120 }
121}
122
123struct QueuedMissingGlyph {
124 generation: usize,
125 missing_glyph: MissingGlyph,
126}
127
128struct MissingGlyphReporter {
130 generation: Arc<AtomicUsize>,
131 sender: async_channel::Sender<QueuedMissingGlyph>,
132}
133
134impl MissingGlyphSink for MissingGlyphReporter {
135 fn report(&self, missing_glyphs: Vec<MissingGlyph>) {
136 if self.sender.is_closed() {
137 return;
138 }
139
140 let generation = self.generation.load(Ordering::Acquire);
141 for missing_glyph in missing_glyphs.into_iter().unique() {
144 let queued = QueuedMissingGlyph {
145 generation,
146 missing_glyph,
147 };
148 if self.sender.try_send(queued).is_err() {
149 break;
150 }
151 }
152 }
153}
154
155impl MissingGlyphReporter {
156 fn reset(&self) {
157 self.generation.fetch_add(1, Ordering::AcqRel);
158 }
159}
160
161pub(crate) struct MissingGlyphReceiver {
163 state: MissingGlyphState,
164 generation: Arc<AtomicUsize>,
165 receiver: async_channel::Receiver<QueuedMissingGlyph>,
166}
167
168impl MissingGlyphReceiver {
169 pub(crate) async fn recv(
175 &mut self,
176 ) -> std::result::Result<Vec<MissingGlyph>, async_channel::RecvError> {
177 loop {
178 let queued = self.receiver.recv().await?;
179 let mut missing_glyphs = Vec::new();
180 for queued in std::iter::once(queued)
181 .chain(std::iter::from_fn(|| self.receiver.try_recv().ok()))
182 .take(MAX_REPORTED_MISSING_GLYPHS)
183 {
184 let generation = self.generation.load(Ordering::Acquire);
185 if self.state.generation != generation {
186 self.state.reset(generation);
187 missing_glyphs.clear();
188 }
189 if queued.generation != generation
190 || !self.state.reported.insert(queued.missing_glyph.clone())
191 {
192 continue;
193 }
194 self.state
195 .reported_order
196 .push_back(queued.missing_glyph.clone());
197 missing_glyphs.push(queued.missing_glyph);
198 if self.state.reported.len() > MAX_REPORTED_MISSING_GLYPHS
199 && let Some(expired) = self.state.reported_order.pop_front()
200 {
201 self.state.reported.remove(&expired);
202 }
203 }
204 if !missing_glyphs.is_empty() {
205 return Ok(missing_glyphs);
206 }
207 let mut yielded = false;
210 std::future::poll_fn(|cx| {
211 if std::mem::replace(&mut yielded, true) {
212 std::task::Poll::Ready(())
213 } else {
214 cx.waker().wake_by_ref();
215 std::task::Poll::Pending
216 }
217 })
218 .await;
219 }
220 }
221}
222
223impl Drop for MissingGlyphReceiver {
224 fn drop(&mut self) {
225 self.receiver.close();
226 while self.receiver.try_recv().is_ok() {}
227 }
228}
229
230pub struct TextSystem {
232 platform_text_system: Arc<dyn PlatformTextSystem>,
233 font_ids_by_font: RwLock<FxHashMap<Font, CachedFont>>,
234 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
235 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
236 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<CharWidthCache>>>,
237 fallback_font_stack: SmallVec<[Font; 2]>,
238 font_generation: Arc<AtomicUsize>,
239 missing_glyph_reporter: Arc<MissingGlyphReporter>,
240 missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,
241}
242
243#[derive(Clone)]
244enum CachedFont {
245 Direct(FontId),
246 Fallback(FontId),
247 Missing(Arc<anyhow::Error>),
248}
249
250impl TextSystem {
251 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
253 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
254 let missing_glyph_generation = Arc::<AtomicUsize>::default();
255 TextSystem {
256 platform_text_system,
257 font_metrics: RwLock::default(),
258 raster_bounds: RwLock::default(),
259 font_ids_by_font: RwLock::default(),
260 wrapper_pool: Mutex::default(),
261 fallback_font_stack: smallvec![
262 font(".ZedMono"),
264 font(".ZedSans"),
265 font("Helvetica"),
266 font("Segoe UI"), font("Ubuntu"), font("Adwaita Sans"), font("Cantarell"), font("Noto Sans"), font("DejaVu Sans"),
272 font("Arial"), ],
274 font_generation: Arc::default(),
275 missing_glyph_reporter: Arc::new(MissingGlyphReporter {
276 generation: missing_glyph_generation.clone(),
277 sender,
278 }),
279 missing_glyph_receiver: Mutex::new(Some(MissingGlyphReceiver {
280 state: MissingGlyphState::default(),
281 generation: missing_glyph_generation,
282 receiver,
283 })),
284 }
285 }
286
287 pub fn all_font_names(&self) -> Vec<String> {
291 let mut names = self.platform_text_system.all_font_names();
292 names.sort_unstable();
293 names.dedup();
294 names
295 }
296
297 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
302 self.platform_text_system.add_fonts(fonts)?;
303 self.font_ids_by_font.write().clear();
304 self.missing_glyph_reporter.reset();
305 self.font_generation.fetch_add(1, Ordering::Release);
306 Ok(())
307 }
308
309 pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
314 self.missing_glyph_receiver
315 .try_lock()
316 .and_then(|mut receiver| receiver.take())
317 }
318
319 pub(crate) fn enable_missing_glyph_reporting(&self) {
320 self.platform_text_system
321 .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
322 }
323
324 pub(crate) fn disable_missing_glyph_reporting(&self) {
325 self.platform_text_system.set_missing_glyph_sink(None);
326 self.missing_glyph_reporter.reset();
327 }
328
329 #[cfg(test)]
330 pub(crate) fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
331 self.missing_glyph_reporter.report(missing_glyphs);
332 }
333
334 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
336 let lock = self.font_ids_by_font.read();
337 lock.iter()
338 .filter_map(|(font, result)| match result {
339 CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),
340 _ => None,
341 })
342 .next()
343 }
344
345 pub fn resolve_font(&self, font: &Font) -> FontId {
352 if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
353 self.font_ids_by_font.read().get(font)
354 {
355 return *font_id;
356 }
357 self.resolve_font_uncached(font)
358 }
359
360 pub fn prewarm_fonts(&self, fonts: &[Font]) {
366 let mut font_ids = SmallVec::<[FontId; 8]>::new();
367 for font in fonts {
368 let font_id = self.resolve_font(font);
369 if !font_ids.contains(&font_id) {
370 font_ids.push(font_id);
371 }
372 }
373 self.platform_text_system.prewarm_fonts(&font_ids);
374 }
375
376 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
380 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
381 }
382
383 pub fn typographic_bounds(
385 &self,
386 font_id: FontId,
387 font_size: Pixels,
388 character: char,
389 ) -> Result<Bounds<Pixels>> {
390 let glyph_id = self
391 .platform_text_system
392 .glyph_for_char(font_id, character)
393 .with_context(|| format!("glyph not found for character '{character}'"))?;
394 let bounds = self
395 .platform_text_system
396 .typographic_bounds(font_id, glyph_id)?;
397 Ok(self.read_metrics(font_id, |metrics| {
398 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
399 }))
400 }
401
402 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
404 let glyph_id = self
405 .platform_text_system
406 .glyph_for_char(font_id, ch)
407 .with_context(|| format!("glyph not found for character '{ch}'"))?;
408 let result = self.platform_text_system.advance(font_id, glyph_id)?
409 / self.units_per_em(font_id) as f32;
410
411 Ok(result * font_size)
412 }
413
414 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
417 let mut buffer = [0; 4];
418 let buffer = ch.encode_utf8(&mut buffer);
419 self.platform_text_system
420 .layout_line(
421 buffer,
422 font_size,
423 &[FontRun {
424 len: buffer.len(),
425 font_id,
426 }],
427 )
428 .width
429 }
430
431 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
435 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
436 }
437
438 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
442 Ok(self.advance(font_id, font_size, 'm')?.width)
443 }
444
445 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
449 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
450 }
451
452 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
456 Ok(self.advance(font_id, font_size, '0')?.width)
457 }
458
459 pub fn units_per_em(&self, font_id: FontId) -> u32 {
463 self.read_metrics(font_id, |metrics| metrics.units_per_em)
464 }
465
466 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
468 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
469 }
470
471 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
473 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
474 }
475
476 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
478 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
479 }
480
481 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
484 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
485 }
486
487 pub fn baseline_offset(
489 &self,
490 font_id: FontId,
491 font_size: Pixels,
492 line_height: Pixels,
493 ) -> Pixels {
494 let ascent = self.ascent(font_id, font_size);
495 let descent = self.descent(font_id, font_size);
496 let padding_top = (line_height - ascent - descent) / 2.;
497 padding_top + ascent
498 }
499
500 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
501 let lock = self.font_metrics.upgradable_read();
502
503 if let Some(metrics) = lock.get(&font_id) {
504 read(metrics)
505 } else {
506 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
507 let metrics = lock
508 .entry(font_id)
509 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
510 read(metrics)
511 }
512 }
513
514 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
516 let lock = &mut self.wrapper_pool.lock();
517 let font_id = self.resolve_font(&font);
518 let char_widths = lock
519 .entry(FontIdWithSize { font_id, font_size })
520 .or_default()
521 .pop()
522 .unwrap_or_default();
523 let wrapper = LineWrapper::new(font_id, font_size, self.clone(), char_widths);
524
525 LineWrapperHandle {
526 wrapper: Some(wrapper),
527 text_system: self.clone(),
528 }
529 }
530
531 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
533 let raster_bounds = self.raster_bounds.upgradable_read();
534 if let Some(bounds) = raster_bounds.get(params) {
535 Ok(*bounds)
536 } else {
537 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
538 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
539 raster_bounds.insert(params.clone(), bounds);
540 Ok(bounds)
541 }
542 }
543
544 pub(crate) fn rasterize_glyph(
545 &self,
546 params: &RenderGlyphParams,
547 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
548 let raster_bounds = self.raster_bounds(params)?;
549 self.platform_text_system
550 .rasterize_glyph(params, raster_bounds)
551 }
552
553 pub fn rasterize_line_alpha(
557 &self,
558 line: &ShapedLine,
559 line_height: Pixels,
560 padding: Pixels,
561 scale: f32,
562 ) -> Result<crate::AlphaMask> {
563 anyhow::ensure!(
564 scale.is_finite() && scale > 0.0 && padding.0 >= 0.0,
565 "invalid line mask scale or padding"
566 );
567 let width = ((line.width.0 + padding.0 * 2.0).max(1.0) * scale).ceil() as i32;
568 let height = ((line_height.0 + padding.0 * 2.0).max(1.0) * scale).ceil() as i32;
569 anyhow::ensure!(
570 width > 0 && height > 0 && (width as u64 * height as u64) <= 16_777_216,
571 "line mask too large"
572 );
573 let mut coverage = vec![0u8; width as usize * height as usize];
574 let baseline =
575 padding.0 + (line_height.0 - line.ascent.0 - line.descent.0) * 0.5 + line.ascent.0;
576 for run in &line.runs {
577 for glyph in &run.glyphs {
578 let params = RenderGlyphParams {
579 font_id: run.font_id,
580 glyph_id: glyph.id,
581 font_size: line.font_size,
582 subpixel_variant: crate::point(0, 0),
583 scale_factor: scale,
584 is_emoji: glyph.is_emoji,
585 subpixel_rendering: false,
586 dilation: 0,
587 };
588 let raster = self.raster_bounds(¶ms)?;
589 if raster.size.width.0 <= 0 || raster.size.height.0 <= 0 {
590 continue;
591 }
592 let (dimensions, bytes) = self.rasterize_glyph(¶ms)?;
593 let channels = if glyph.is_emoji { 4 } else { 1 };
594 anyhow::ensure!(
595 bytes.len()
596 == dimensions.width.0 as usize * dimensions.height.0 as usize * channels,
597 "invalid glyph coverage"
598 );
599 let left =
600 ((padding.0 + glyph.position.x.0) * scale).round() as i32 + raster.origin.x.0;
601 let top =
602 ((baseline + glyph.position.y.0) * scale).round() as i32 + raster.origin.y.0;
603 for y in 0..dimensions.height.0 {
604 let dy = top + y;
605 if dy < 0 || dy >= height {
606 continue;
607 }
608 for x in 0..dimensions.width.0 {
609 let dx = left + x;
610 if dx < 0 || dx >= width {
611 continue;
612 }
613 let src = bytes[(y as usize * dimensions.width.0 as usize + x as usize)
614 * channels
615 + channels
616 - 1] as u32;
617 let dst = &mut coverage[dy as usize * width as usize + dx as usize];
618 *dst = (src + (*dst as u32 * (255 - src) + 127) / 255) as u8;
619 }
620 }
621 }
622 }
623 crate::AlphaMask::new(
624 crate::size(DevicePixels(width), DevicePixels(height)),
625 coverage.into(),
626 )
627 }
628
629 pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
631 self.platform_text_system.glyph_dilation_for_color(color)
632 }
633
634 pub(crate) fn recommended_rendering_mode(
637 &self,
638 font_id: FontId,
639 font_size: Pixels,
640 ) -> TextRenderingMode {
641 self.platform_text_system
642 .recommended_rendering_mode(font_id, font_size)
643 }
644
645 fn resolve_font_uncached(&self, font: &Font) -> FontId {
646 let mut font_error = None;
647 let font_id = {
648 let mut font_ids = self.font_ids_by_font.upgradable_read();
649 if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
650 font_ids.get(font)
651 {
652 return *font_id;
653 }
654
655 let mut lookup_font = |candidate: &Font| {
656 let cached = if let Some(cached) = font_ids.get(candidate) {
657 cached.clone()
658 } else {
659 let cached = match self.platform_text_system.font_id(candidate) {
660 Ok(font_id) => CachedFont::Direct(font_id),
661 Err(error) => CachedFont::Missing(Arc::new(error)),
662 };
663 font_ids.with_upgraded(|font_ids| {
664 font_ids.insert(candidate.clone(), cached.clone());
665 });
666 cached
667 };
668 match cached {
669 CachedFont::Direct(font_id) => Some(font_id),
670 CachedFont::Fallback(_) => None,
671 CachedFont::Missing(error) => {
672 if candidate == font {
673 font_error = Some(error);
674 }
675 None
676 }
677 }
678 };
679
680 if let Some(font_id) = lookup_font(font) {
681 Some(font_id)
682 } else {
683 let font_id = self.fallback_font_stack.iter().find_map(lookup_font);
684 if let Some(font_id) = font_id {
685 font_ids.with_upgraded(|font_ids| {
686 font_ids.insert(font.clone(), CachedFont::Fallback(font_id));
687 });
688 }
689 font_id
690 }
691 };
692 if let Some(error) = font_error {
693 log::warn!("failed to load font {font:?}: {error:#}");
694 }
695 font_id.unwrap_or_else(|| {
696 panic!(
697 "failed to resolve font '{}' or any of the fallbacks: {}",
698 font.family,
699 self.fallback_font_stack
700 .iter()
701 .map(|fallback| &fallback.family)
702 .join(", ")
703 );
704 })
705 }
706}
707
708#[derive(Deref)]
710pub struct WindowTextSystem {
711 line_layout_cache: LineLayoutCache,
712 font_runs_buffer: Cell<Vec<FontRun>>,
713 #[deref]
714 text_system: Arc<TextSystem>,
715}
716
717impl WindowTextSystem {
718 pub fn new(text_system: Arc<TextSystem>) -> Self {
720 Self {
721 line_layout_cache: LineLayoutCache::new(
722 text_system.platform_text_system.clone(),
723 text_system.font_generation.clone(),
724 ),
725 font_runs_buffer: Cell::default(),
726 text_system,
727 }
728 }
729
730 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
731 self.line_layout_cache.layout_index()
732 }
733
734 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
735 self.line_layout_cache.reuse_layouts(index)
736 }
737
738 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
739 self.line_layout_cache.truncate_layouts(index)
740 }
741
742 pub fn shape_line(
749 &self,
750 text: SharedString,
751 font_size: Pixels,
752 runs: &[TextRun],
753 force_width: Option<Pixels>,
754 ) -> ShapedLine {
755 debug_assert!(
756 text.find('\n').is_none(),
757 "text argument should not contain newlines"
758 );
759
760 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
761 for run in runs {
762 if let Some(last_run) = decoration_runs.last_mut()
763 && last_run.color == run.color
764 && last_run.underline == run.underline
765 && last_run.strikethrough == run.strikethrough
766 && last_run.background_color == run.background_color
767 {
768 last_run.len += run.len as u32;
769 continue;
770 }
771 decoration_runs.push(DecorationRun {
772 len: run.len as u32,
773 color: run.color,
774 background_color: run.background_color,
775 underline: run.underline,
776 strikethrough: run.strikethrough,
777 });
778 }
779
780 let layout = self.layout_line(&text, font_size, runs, force_width);
781
782 ShapedLine {
783 layout,
784 text,
785 decoration_runs,
786 }
787 }
788
789 pub fn shape_text(
793 &self,
794 text: SharedString,
795 font_size: Pixels,
796 runs: &[TextRun],
797 wrap_width: Option<Pixels>,
798 line_clamp: Option<usize>,
799 ) -> Result<SmallVec<[WrappedLine; 1]>> {
800 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
801 let mut font_runs = self.font_runs_buffer.take();
802
803 let mut lines = SmallVec::new();
804 let max_wrap_lines = line_clamp;
805 let mut wrapped_lines = 0;
806
807 let mut process_line = |line_text: SharedString, line_start, line_end| {
808 font_runs.clear();
809
810 let mut decoration_runs = <Vec<DecorationRun>>::new();
811 let mut run_start = line_start;
812 while run_start < line_end {
813 let Some(run) = runs.peek_mut() else {
814 log::warn!("`TextRun`s do not cover the entire to be shaped text");
815 break;
816 };
817
818 let run_len_within_line = cmp::min(line_end - run_start, run.len);
819
820 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
821 && last_run.color == run.color
822 && last_run.underline == run.underline
823 && last_run.strikethrough == run.strikethrough
824 && last_run.background_color == run.background_color
825 {
826 last_run.len += run_len_within_line as u32;
827 false
828 } else {
829 decoration_runs.push(DecorationRun {
830 len: run_len_within_line as u32,
831 color: run.color,
832 background_color: run.background_color,
833 underline: run.underline,
834 strikethrough: run.strikethrough,
835 });
836 true
837 };
838
839 let font_id = self.resolve_font(&run.font);
840 if let Some(font_run) = font_runs.last_mut()
841 && font_id == font_run.font_id
842 && !decoration_changed
843 {
844 font_run.len += run_len_within_line;
845 } else {
846 font_runs.push(FontRun {
847 len: run_len_within_line,
848 font_id,
849 });
850 }
851
852 run.len -= run_len_within_line;
854 if run.len == 0 {
855 runs.next();
856 }
857 run_start += run_len_within_line;
858 }
859
860 let layout = self.line_layout_cache.layout_wrapped_line(
861 &line_text,
862 font_size,
863 &font_runs,
864 wrap_width,
865 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
866 );
867 wrapped_lines += layout.wrap_boundaries.len();
868
869 lines.push(WrappedLine {
870 layout,
871 decoration_runs,
872 text: line_text,
873 });
874
875 if let Some(run) = runs.peek_mut() {
877 run.len -= 1;
878 if run.len == 0 {
879 runs.next();
880 }
881 }
882 };
883
884 let mut split_lines = text.split('\n');
885
886 if let Some(first_line) = split_lines.next()
888 && let Some(second_line) = split_lines.next()
889 {
890 let mut line_start = 0;
891 process_line(
892 SharedString::new(first_line),
893 line_start,
894 line_start + first_line.len(),
895 );
896 line_start += first_line.len() + '\n'.len_utf8();
897 process_line(
898 SharedString::new(second_line),
899 line_start,
900 line_start + second_line.len(),
901 );
902 for line_text in split_lines {
903 line_start += line_text.len() + '\n'.len_utf8();
904 process_line(
905 SharedString::new(line_text),
906 line_start,
907 line_start + line_text.len(),
908 );
909 }
910 } else {
911 let end = text.len();
912 process_line(text, 0, end);
913 }
914
915 self.font_runs_buffer.set(font_runs);
916
917 Ok(lines)
918 }
919
920 pub(crate) fn finish_frame(&self) {
921 self.line_layout_cache.finish_frame()
922 }
923
924 pub fn layout_line<Text>(
929 &self,
930 text: Text,
931 font_size: Pixels,
932 runs: &[TextRun],
933 force_width: Option<Pixels>,
934 ) -> Arc<LineLayout>
935 where
936 Text: AsRef<str>,
937 SharedString: From<Text>,
938 {
939 let font_runs = self.font_runs(runs);
940 let layout = self
941 .line_layout_cache
942 .layout_line(text, font_size, &font_runs, force_width);
943 self.font_runs_buffer.set(font_runs);
944 layout
945 }
946
947 fn font_runs(&self, runs: &[TextRun]) -> Vec<FontRun> {
948 let mut last_run = None::<&TextRun>;
949 let mut font_runs = self.font_runs_buffer.take();
950 font_runs.clear();
951
952 for run in runs.iter() {
953 let decoration_changed = if let Some(last_run) = last_run
954 && last_run.color == run.color
955 && last_run.underline == run.underline
956 && last_run.strikethrough == run.strikethrough
957 {
960 false
961 } else {
962 last_run = Some(run);
963 true
964 };
965
966 let font_id = self.resolve_font(&run.font);
967 if let Some(font_run) = font_runs.last_mut()
968 && font_id == font_run.font_id
969 && !decoration_changed
970 {
971 font_run.len += run.len;
972 } else {
973 font_runs.push(FontRun {
974 len: run.len,
975 font_id,
976 });
977 }
978 }
979
980 font_runs
981 }
982
983 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
985 let mut buffer = [0; 4];
986 let buffer: &_ = ch.encode_utf8(&mut buffer);
987 self.line_layout_cache
988 .layout_line(
989 buffer,
990 font_size,
991 &[FontRun {
992 len: buffer.len(),
993 font_id,
994 }],
995 None,
996 )
997 .width
998 }
999
1000 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
1002 self.layout_width(font_id, font_size, 'm')
1003 }
1004}
1005
1006#[derive(Hash, Eq, PartialEq)]
1007struct FontIdWithSize {
1008 font_id: FontId,
1009 font_size: Pixels,
1010}
1011
1012pub struct LineWrapperHandle {
1014 wrapper: Option<LineWrapper>,
1015 text_system: Arc<TextSystem>,
1016}
1017
1018impl Drop for LineWrapperHandle {
1019 fn drop(&mut self) {
1020 let mut state = self.text_system.wrapper_pool.lock();
1021 let wrapper = self.wrapper.take().unwrap();
1022 state
1023 .get_mut(&FontIdWithSize {
1024 font_id: wrapper.font_id,
1025 font_size: wrapper.font_size,
1026 })
1027 .unwrap()
1028 .push(wrapper.into_char_widths());
1029 }
1030}
1031
1032impl Deref for LineWrapperHandle {
1033 type Target = LineWrapper;
1034
1035 fn deref(&self) -> &Self::Target {
1036 self.wrapper.as_ref().unwrap()
1037 }
1038}
1039
1040impl DerefMut for LineWrapperHandle {
1041 fn deref_mut(&mut self) -> &mut Self::Target {
1042 self.wrapper.as_mut().unwrap()
1043 }
1044}
1045
1046#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
1049#[serde(transparent)]
1050pub struct FontWeight(pub f32);
1051
1052impl Display for FontWeight {
1053 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1054 write!(f, "{}", self.0)
1055 }
1056}
1057
1058impl From<f32> for FontWeight {
1059 fn from(weight: f32) -> Self {
1060 FontWeight(weight)
1061 }
1062}
1063
1064impl Default for FontWeight {
1065 #[inline]
1066 fn default() -> FontWeight {
1067 FontWeight::NORMAL
1068 }
1069}
1070
1071impl Hash for FontWeight {
1072 fn hash<H: Hasher>(&self, state: &mut H) {
1073 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
1074 }
1075}
1076
1077impl Eq for FontWeight {}
1078
1079impl FontWeight {
1080 pub const THIN: FontWeight = FontWeight(100.0);
1082 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1084 pub const LIGHT: FontWeight = FontWeight(300.0);
1086 pub const NORMAL: FontWeight = FontWeight(400.0);
1088 pub const MEDIUM: FontWeight = FontWeight(500.0);
1090 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1092 pub const BOLD: FontWeight = FontWeight(700.0);
1094 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1096 pub const BLACK: FontWeight = FontWeight(900.0);
1098
1099 pub const ALL: [FontWeight; 9] = [
1101 Self::THIN,
1102 Self::EXTRA_LIGHT,
1103 Self::LIGHT,
1104 Self::NORMAL,
1105 Self::MEDIUM,
1106 Self::SEMIBOLD,
1107 Self::BOLD,
1108 Self::EXTRA_BOLD,
1109 Self::BLACK,
1110 ];
1111}
1112
1113impl schemars::JsonSchema for FontWeight {
1114 fn schema_name() -> std::borrow::Cow<'static, str> {
1115 "FontWeight".into()
1116 }
1117
1118 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1119 use schemars::json_schema;
1120 json_schema!({
1121 "type": "number",
1122 "minimum": Self::THIN,
1123 "maximum": Self::BLACK,
1124 "default": Self::default(),
1125 "description": "Font weight value between 100 (thin) and 900 (black)"
1126 })
1127 }
1128}
1129
1130#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1132pub enum FontStyle {
1133 #[default]
1135 Normal,
1136 Italic,
1138 Oblique,
1140}
1141
1142impl Display for FontStyle {
1143 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1144 Debug::fmt(self, f)
1145 }
1146}
1147
1148#[derive(Clone, Debug, PartialEq, Eq, Default)]
1150pub struct TextRun {
1151 pub len: usize,
1153 pub font: Font,
1155 pub color: Hsla,
1157 pub background_color: Option<Hsla>,
1159 pub underline: Option<UnderlineStyle>,
1161 pub strikethrough: Option<StrikethroughStyle>,
1163}
1164
1165#[cfg(all(target_os = "macos", test))]
1166impl TextRun {
1167 fn with_len(&self, len: usize) -> Self {
1168 let mut this = self.clone();
1169 this.len = len;
1170 this
1171 }
1172}
1173
1174#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1176#[repr(C)]
1177pub struct GlyphId(pub u32);
1178
1179#[derive(Clone, Debug, PartialEq)]
1185#[expect(missing_docs)]
1186pub struct RenderGlyphParams {
1187 pub font_id: FontId,
1188 pub glyph_id: GlyphId,
1189 pub font_size: Pixels,
1190 pub subpixel_variant: Point<u8>,
1191 pub scale_factor: f32,
1192 pub is_emoji: bool,
1193 pub subpixel_rendering: bool,
1194 pub dilation: u8,
1195}
1196
1197impl Eq for RenderGlyphParams {}
1198
1199impl Hash for RenderGlyphParams {
1200 fn hash<H: Hasher>(&self, state: &mut H) {
1201 self.font_id.0.hash(state);
1202 self.glyph_id.0.hash(state);
1203 self.font_size.0.to_bits().hash(state);
1204 self.subpixel_variant.hash(state);
1205 self.scale_factor.to_bits().hash(state);
1206 self.is_emoji.hash(state);
1207 self.subpixel_rendering.hash(state);
1208 self.dilation.hash(state);
1209 }
1210}
1211
1212#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1214pub struct Font {
1215 pub family: SharedString,
1219
1220 pub features: FontFeatures,
1222
1223 pub fallbacks: Option<FontFallbacks>,
1225
1226 pub weight: FontWeight,
1228
1229 pub style: FontStyle,
1231}
1232
1233impl Default for Font {
1234 fn default() -> Self {
1235 font(".SystemUIFont")
1236 }
1237}
1238
1239pub fn font(family: impl Into<SharedString>) -> Font {
1241 Font {
1242 family: family.into(),
1243 features: FontFeatures::default(),
1244 weight: FontWeight::default(),
1245 style: FontStyle::default(),
1246 fallbacks: None,
1247 }
1248}
1249
1250impl Font {
1251 pub fn bold(mut self) -> Self {
1253 self.weight = FontWeight::BOLD;
1254 self
1255 }
1256
1257 pub fn italic(mut self) -> Self {
1259 self.style = FontStyle::Italic;
1260 self
1261 }
1262}
1263
1264#[derive(Clone, Copy, Debug)]
1267pub struct FontMetrics {
1268 pub units_per_em: u32,
1271
1272 pub ascent: f32,
1274
1275 pub descent: f32,
1277
1278 pub line_gap: f32,
1280
1281 pub underline_position: f32,
1283
1284 pub underline_thickness: f32,
1286
1287 pub cap_height: f32,
1289
1290 pub x_height: f32,
1292
1293 pub bounding_box: Bounds<f32>,
1296}
1297
1298impl FontMetrics {
1299 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1301 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1302 }
1303
1304 pub fn descent(&self, font_size: Pixels) -> Pixels {
1306 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1307 }
1308
1309 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1311 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1312 }
1313
1314 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1316 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1317 }
1318
1319 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1321 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1322 }
1323
1324 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1326 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1327 }
1328
1329 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1331 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1332 }
1333
1334 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1336 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1337 }
1338}
1339
1340#[allow(unused)]
1342pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1343 match name {
1347 ".SystemUIFont" => system,
1348 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1349 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1350 _ => name,
1351 }
1352}
1353
1354#[allow(unused)]
1356pub fn font_name_with_fallbacks_shared<'a>(
1357 name: &'a SharedString,
1358 system: &'a SharedString,
1359) -> &'a SharedString {
1360 match name.as_str() {
1364 ".SystemUIFont" => system,
1365 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1366 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1367 _ => name,
1368 }
1369}
1370
1371#[cfg(test)]
1372mod font_resolution_tests {
1373 use super::*;
1374 use crate::NoopTextSystem;
1375
1376 #[test]
1377 fn caches_resolved_font_fallbacks() {
1378 let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));
1379 let requested = font("Missing Font").bold().italic();
1380 let missing = CachedFont::Missing(Arc::new(anyhow::anyhow!("missing font")));
1381 {
1382 let mut font_ids = text_system.font_ids_by_font.write();
1383 font_ids.insert(requested.clone(), missing.clone());
1384 for fallback in &text_system.fallback_font_stack {
1385 font_ids.insert(fallback.clone(), missing.clone());
1386 }
1387 font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));
1388 }
1389
1390 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1391 assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));
1392
1393 text_system.fallback_font_stack.clear();
1394 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1395 }
1396}
1397
1398#[cfg(test)]
1399mod line_wrapper_pool_tests {
1400 use super::*;
1401 use crate::NoopTextSystem;
1402
1403 #[test]
1404 fn pooled_line_wrappers_do_not_retain_text_system() {
1405 let text_system = Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new())));
1406 let weak_text_system = Arc::downgrade(&text_system);
1407
1408 let mut wrapper = text_system.line_wrapper(font(".ZedMono"), px(16.));
1409 let fragments = [LineFragment::text("hello world")];
1410 wrapper
1411 .wrap_line(&fragments, px(40.), IndentAdjustment::default())
1412 .for_each(drop);
1413 drop(wrapper);
1414 drop(text_system);
1415
1416 assert!(weak_text_system.upgrade().is_none());
1417 }
1418}
1419
1420#[cfg(test)]
1421mod missing_glyph_tests {
1422 use super::*;
1423 use futures::FutureExt as _;
1424
1425 #[test]
1426 fn bounds_retained_missing_glyphs() {
1427 let (reporter, mut receiver) = missing_glyph_channel();
1428 reporter.report(
1429 (0..MAX_REPORTED_MISSING_GLYPHS)
1430 .map(|index| {
1431 MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1432 })
1433 .collect(),
1434 );
1435 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1436
1437 let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1438 reporter.report(vec![newest.clone()]);
1439 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1440
1441 let state = &receiver.state;
1442 assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1443 assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1444 assert!(state.reported.contains(&newest));
1445 }
1446
1447 #[test]
1448 fn dropping_receiver_closes_and_clears_reports() {
1449 let (reporter, receiver) = missing_glyph_channel();
1450 reporter.report(vec![missing_glyph("missing")]);
1451
1452 drop(receiver);
1453
1454 assert!(reporter.sender.is_closed());
1455 assert!(reporter.sender.is_empty());
1456 }
1457
1458 fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1459 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1460 let generation = Arc::<AtomicUsize>::default();
1461 let reporter = MissingGlyphReporter {
1462 generation: generation.clone(),
1463 sender,
1464 };
1465 let receiver = MissingGlyphReceiver {
1466 state: MissingGlyphState::default(),
1467 generation,
1468 receiver,
1469 };
1470 (reporter, receiver)
1471 }
1472
1473 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1474 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1475 }
1476}