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