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