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 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 pub(crate) platform_text_system: Arc<dyn PlatformTextSystem>,
234 pub(crate) 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 pub(crate) 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)]
245pub(crate) enum 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 crate::fast::text::fonts_changed();
304 self.platform_text_system.add_fonts(fonts)?;
305 self.font_ids_by_font.write().clear();
306 self.missing_glyph_reporter.reset();
307 self.font_generation.fetch_add(1, Ordering::Release);
308 Ok(())
309 }
310
311 pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
316 self.missing_glyph_receiver
317 .try_lock()
318 .and_then(|mut receiver| receiver.take())
319 }
320
321 pub(crate) fn enable_missing_glyph_reporting(&self) {
322 self.platform_text_system
323 .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
324 }
325
326 pub(crate) fn disable_missing_glyph_reporting(&self) {
327 self.platform_text_system.set_missing_glyph_sink(None);
328 self.missing_glyph_reporter.reset();
329 }
330
331 #[cfg(test)]
332 pub(crate) fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
333 self.missing_glyph_reporter.report(missing_glyphs);
334 }
335
336 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
338 let lock = self.font_ids_by_font.read();
339 lock.iter()
340 .filter_map(|(font, result)| match result {
341 CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),
342 _ => None,
343 })
344 .next()
345 }
346
347 pub fn resolve_font(&self, font: &Font) -> FontId {
354 crate::fast::text::resolve_font(self, font)
355 }
356
357 pub fn prewarm_fonts(&self, fonts: &[Font]) {
363 let mut font_ids = SmallVec::<[FontId; 8]>::new();
364 for font in fonts {
365 let font_id = self.resolve_font(font);
366 if !font_ids.contains(&font_id) {
367 font_ids.push(font_id);
368 }
369 }
370 self.platform_text_system.prewarm_fonts(&font_ids);
371 }
372
373 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
377 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
378 }
379
380 pub fn typographic_bounds(
382 &self,
383 font_id: FontId,
384 font_size: Pixels,
385 character: char,
386 ) -> Result<Bounds<Pixels>> {
387 let glyph_id = self
388 .platform_text_system
389 .glyph_for_char(font_id, character)
390 .with_context(|| format!("glyph not found for character '{character}'"))?;
391 let bounds = self
392 .platform_text_system
393 .typographic_bounds(font_id, glyph_id)?;
394 Ok(self.read_metrics(font_id, |metrics| {
395 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
396 }))
397 }
398
399 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
401 let glyph_id = self
402 .platform_text_system
403 .glyph_for_char(font_id, ch)
404 .with_context(|| format!("glyph not found for character '{ch}'"))?;
405 let result = self.platform_text_system.advance(font_id, glyph_id)?
406 / self.units_per_em(font_id) as f32;
407
408 Ok(result * font_size)
409 }
410
411 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
414 let mut buffer = [0; 4];
415 let buffer = ch.encode_utf8(&mut buffer);
416 self.platform_text_system
417 .layout_line(
418 buffer,
419 font_size,
420 &[FontRun {
421 len: buffer.len(),
422 font_id,
423 }],
424 )
425 .width
426 }
427
428 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
432 crate::fast::em_metrics::em_width(self, font_id, font_size)
433 }
434
435 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
439 crate::fast::em_metrics::em_advance(self, font_id, font_size)
440 }
441
442 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
446 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
447 }
448
449 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
453 Ok(self.advance(font_id, font_size, '0')?.width)
454 }
455
456 pub fn units_per_em(&self, font_id: FontId) -> u32 {
460 self.read_metrics(font_id, |metrics| metrics.units_per_em)
461 }
462
463 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
465 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
466 }
467
468 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
470 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
471 }
472
473 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
475 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
476 }
477
478 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
481 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
482 }
483
484 pub fn baseline_offset(
486 &self,
487 font_id: FontId,
488 font_size: Pixels,
489 line_height: Pixels,
490 ) -> Pixels {
491 let ascent = self.ascent(font_id, font_size);
492 let descent = self.descent(font_id, font_size);
493 let padding_top = (line_height - ascent - descent) / 2.;
494 padding_top + ascent
495 }
496
497 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
498 let lock = self.font_metrics.upgradable_read();
499
500 if let Some(metrics) = lock.get(&font_id) {
501 read(metrics)
502 } else {
503 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
504 let metrics = lock
505 .entry(font_id)
506 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
507 read(metrics)
508 }
509 }
510
511 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
513 let lock = &mut self.wrapper_pool.lock();
514 let font_id = self.resolve_font(&font);
515 let char_widths = lock
516 .entry(FontIdWithSize { font_id, font_size })
517 .or_default()
518 .pop()
519 .unwrap_or_default();
520 let wrapper = LineWrapper::new(font_id, font_size, self.clone(), char_widths);
521
522 LineWrapperHandle {
523 wrapper: Some(wrapper),
524 text_system: self.clone(),
525 }
526 }
527
528 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
530 let raster_bounds = self.raster_bounds.upgradable_read();
531 if let Some(bounds) = raster_bounds.get(params) {
532 Ok(*bounds)
533 } else {
534 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
535 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
536 raster_bounds.insert(params.clone(), bounds);
537 Ok(bounds)
538 }
539 }
540
541 pub(crate) fn rasterize_glyph(
542 &self,
543 params: &RenderGlyphParams,
544 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
545 let raster_bounds = self.raster_bounds(params)?;
546 self.platform_text_system
547 .rasterize_glyph(params, raster_bounds)
548 }
549
550 pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
552 self.platform_text_system.glyph_dilation_for_color(color)
553 }
554
555 pub(crate) fn recommended_rendering_mode(
558 &self,
559 font_id: FontId,
560 font_size: Pixels,
561 ) -> TextRenderingMode {
562 self.platform_text_system
563 .recommended_rendering_mode(font_id, font_size)
564 }
565
566 pub(crate) fn resolve_font_uncached(&self, font: &Font) -> FontId {
567 let mut font_error = None;
568 let font_id = {
569 let mut font_ids = self.font_ids_by_font.upgradable_read();
570 if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
571 font_ids.get(font)
572 {
573 return *font_id;
574 }
575
576 let mut lookup_font = |candidate: &Font| {
577 let cached = if let Some(cached) = font_ids.get(candidate) {
578 cached.clone()
579 } else {
580 let cached = match self.platform_text_system.font_id(candidate) {
581 Ok(font_id) => CachedFont::Direct(font_id),
582 Err(error) => CachedFont::Missing(Arc::new(error)),
583 };
584 font_ids.with_upgraded(|font_ids| {
585 font_ids.insert(candidate.clone(), cached.clone());
586 });
587 cached
588 };
589 match cached {
590 CachedFont::Direct(font_id) => Some(font_id),
591 CachedFont::Fallback(_) => None,
592 CachedFont::Missing(error) => {
593 if candidate == font {
594 font_error = Some(error);
595 }
596 None
597 }
598 }
599 };
600
601 if let Some(font_id) = lookup_font(font) {
602 Some(font_id)
603 } else {
604 let font_id = self.fallback_font_stack.iter().find_map(lookup_font);
605 if let Some(font_id) = font_id {
606 font_ids.with_upgraded(|font_ids| {
607 font_ids.insert(font.clone(), CachedFont::Fallback(font_id));
608 });
609 }
610 font_id
611 }
612 };
613 if let Some(error) = font_error {
614 log::warn!("failed to load font {font:?}: {error:#}");
615 }
616 font_id.unwrap_or_else(|| {
617 panic!(
618 "failed to resolve font '{}' or any of the fallbacks: {}",
619 font.family,
620 self.fallback_font_stack
621 .iter()
622 .map(|fallback| &fallback.family)
623 .join(", ")
624 );
625 })
626 }
627}
628
629#[derive(Deref)]
631pub struct WindowTextSystem {
632 pub(crate) line_layout_cache: LineLayoutCache,
633 font_runs_buffer: Cell<Vec<FontRun>>,
634 #[deref]
635 text_system: Arc<TextSystem>,
636}
637
638impl WindowTextSystem {
639 pub fn new(text_system: Arc<TextSystem>) -> Self {
641 Self {
642 line_layout_cache: LineLayoutCache::new(
643 text_system.platform_text_system.clone(),
644 text_system.font_generation.clone(),
645 ),
646 font_runs_buffer: Cell::default(),
647 text_system,
648 }
649 }
650
651 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
652 self.line_layout_cache.layout_index()
653 }
654
655 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
656 self.line_layout_cache.reuse_layouts(index)
657 }
658
659 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
660 self.line_layout_cache.truncate_layouts(index)
661 }
662
663 pub fn shape_line(
670 &self,
671 text: SharedString,
672 font_size: Pixels,
673 runs: &[TextRun],
674 force_width: Option<Pixels>,
675 ) -> ShapedLine {
676 debug_assert!(
677 text.find('\n').is_none(),
678 "text argument should not contain newlines"
679 );
680
681 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
682 for run in runs {
683 if let Some(last_run) = decoration_runs.last_mut()
684 && last_run.color == run.color
685 && last_run.underline == run.underline
686 && last_run.strikethrough == run.strikethrough
687 && last_run.background_color == run.background_color
688 {
689 last_run.len += run.len as u32;
690 continue;
691 }
692 decoration_runs.push(DecorationRun {
693 len: run.len as u32,
694 color: run.color,
695 background_color: run.background_color,
696 underline: run.underline,
697 strikethrough: run.strikethrough,
698 });
699 }
700
701 let layout = self.layout_line(&text, font_size, runs, force_width);
702
703 ShapedLine {
704 layout,
705 text,
706 decoration_runs,
707 }
708 }
709
710 pub fn shape_text(
714 &self,
715 text: SharedString,
716 font_size: Pixels,
717 runs: &[TextRun],
718 wrap_width: Option<Pixels>,
719 line_clamp: Option<usize>,
720 ) -> Result<SmallVec<[WrappedLine; 1]>> {
721 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
722 let mut font_runs = self.font_runs_buffer.take();
723
724 let mut lines = SmallVec::new();
725 let max_wrap_lines = line_clamp;
726 let mut wrapped_lines = 0;
727
728 let mut process_line = |line_text: SharedString, line_start, line_end| {
729 font_runs.clear();
730
731 let mut decoration_runs = crate::fast::text::decoration_runs();
732 let mut run_start = line_start;
733 while run_start < line_end {
734 let Some(run) = runs.peek_mut() else {
735 log::warn!("`TextRun`s do not cover the entire to be shaped text");
736 break;
737 };
738
739 let run_len_within_line = cmp::min(line_end - run_start, run.len);
740
741 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
742 && last_run.color == run.color
743 && last_run.underline == run.underline
744 && last_run.strikethrough == run.strikethrough
745 && last_run.background_color == run.background_color
746 {
747 last_run.len += run_len_within_line as u32;
748 false
749 } else {
750 decoration_runs.push(DecorationRun {
751 len: run_len_within_line as u32,
752 color: run.color,
753 background_color: run.background_color,
754 underline: run.underline,
755 strikethrough: run.strikethrough,
756 });
757 true
758 };
759
760 let font_id = self.resolve_font(&run.font);
761 if let Some(font_run) = font_runs.last_mut()
762 && font_id == font_run.font_id
763 && !decoration_changed
764 {
765 font_run.len += run_len_within_line;
766 } else {
767 font_runs.push(FontRun {
768 len: run_len_within_line,
769 font_id,
770 });
771 }
772
773 run.len -= run_len_within_line;
775 if run.len == 0 {
776 runs.next();
777 }
778 run_start += run_len_within_line;
779 }
780
781 let layout = self.line_layout_cache.layout_wrapped_line(
782 &line_text,
783 font_size,
784 &font_runs,
785 wrap_width,
786 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
787 );
788 wrapped_lines += layout.wrap_boundaries.len();
789
790 lines.push(WrappedLine {
791 layout,
792 decoration_runs,
793 text: line_text,
794 });
795
796 if let Some(run) = runs.peek_mut() {
798 run.len -= 1;
799 if run.len == 0 {
800 runs.next();
801 }
802 }
803 };
804
805 let mut split_lines = text.split('\n');
806
807 if let Some(first_line) = split_lines.next()
809 && let Some(second_line) = split_lines.next()
810 {
811 let mut line_start = 0;
812 process_line(
813 SharedString::new(first_line),
814 line_start,
815 line_start + first_line.len(),
816 );
817 line_start += first_line.len() + '\n'.len_utf8();
818 process_line(
819 SharedString::new(second_line),
820 line_start,
821 line_start + second_line.len(),
822 );
823 for line_text in split_lines {
824 line_start += line_text.len() + '\n'.len_utf8();
825 process_line(
826 SharedString::new(line_text),
827 line_start,
828 line_start + line_text.len(),
829 );
830 }
831 } else {
832 let end = text.len();
833 process_line(text, 0, end);
834 }
835
836 self.font_runs_buffer.set(font_runs);
837
838 Ok(lines)
839 }
840
841 pub(crate) fn finish_frame(&self) {
842 self.line_layout_cache.finish_frame()
843 }
844
845 pub fn layout_line<Text>(
850 &self,
851 text: Text,
852 font_size: Pixels,
853 runs: &[TextRun],
854 force_width: Option<Pixels>,
855 ) -> Arc<LineLayout>
856 where
857 Text: AsRef<str>,
858 SharedString: From<Text>,
859 {
860 let font_runs = self.font_runs(runs);
861 let layout = self
862 .line_layout_cache
863 .layout_line(text, font_size, &font_runs, force_width);
864 self.font_runs_buffer.set(font_runs);
865 layout
866 }
867
868 fn font_runs(&self, runs: &[TextRun]) -> Vec<FontRun> {
869 let mut last_run = None::<&TextRun>;
870 let mut font_runs = self.font_runs_buffer.take();
871 font_runs.clear();
872
873 for run in runs.iter() {
874 let decoration_changed = if let Some(last_run) = last_run
875 && last_run.color == run.color
876 && last_run.underline == run.underline
877 && last_run.strikethrough == run.strikethrough
878 {
881 false
882 } else {
883 last_run = Some(run);
884 true
885 };
886
887 let font_id = self.resolve_font(&run.font);
888 if let Some(font_run) = font_runs.last_mut()
889 && font_id == font_run.font_id
890 && !decoration_changed
891 {
892 font_run.len += run.len;
893 } else {
894 font_runs.push(FontRun {
895 len: run.len,
896 font_id,
897 });
898 }
899 }
900
901 font_runs
902 }
903
904 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
906 let mut buffer = [0; 4];
907 let buffer: &_ = ch.encode_utf8(&mut buffer);
908 self.line_layout_cache
909 .layout_line(
910 buffer,
911 font_size,
912 &[FontRun {
913 len: buffer.len(),
914 font_id,
915 }],
916 None,
917 )
918 .width
919 }
920
921 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
923 self.layout_width(font_id, font_size, 'm')
924 }
925}
926
927#[derive(Hash, Eq, PartialEq)]
928struct FontIdWithSize {
929 font_id: FontId,
930 font_size: Pixels,
931}
932
933pub struct LineWrapperHandle {
935 wrapper: Option<LineWrapper>,
936 text_system: Arc<TextSystem>,
937}
938
939impl Drop for LineWrapperHandle {
940 fn drop(&mut self) {
941 let mut state = self.text_system.wrapper_pool.lock();
942 let wrapper = self.wrapper.take().unwrap();
943 state
944 .get_mut(&FontIdWithSize {
945 font_id: wrapper.font_id,
946 font_size: wrapper.font_size,
947 })
948 .unwrap()
949 .push(wrapper.into_char_widths());
950 }
951}
952
953impl Deref for LineWrapperHandle {
954 type Target = LineWrapper;
955
956 fn deref(&self) -> &Self::Target {
957 self.wrapper.as_ref().unwrap()
958 }
959}
960
961impl DerefMut for LineWrapperHandle {
962 fn deref_mut(&mut self) -> &mut Self::Target {
963 self.wrapper.as_mut().unwrap()
964 }
965}
966
967#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
970#[serde(transparent)]
971pub struct FontWeight(pub f32);
972
973impl Display for FontWeight {
974 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
975 write!(f, "{}", self.0)
976 }
977}
978
979impl From<f32> for FontWeight {
980 fn from(weight: f32) -> Self {
981 FontWeight(weight)
982 }
983}
984
985impl Default for FontWeight {
986 #[inline]
987 fn default() -> FontWeight {
988 FontWeight::NORMAL
989 }
990}
991
992impl Hash for FontWeight {
993 fn hash<H: Hasher>(&self, state: &mut H) {
994 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
995 }
996}
997
998impl Eq for FontWeight {}
999
1000impl FontWeight {
1001 pub const THIN: FontWeight = FontWeight(100.0);
1003 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1005 pub const LIGHT: FontWeight = FontWeight(300.0);
1007 pub const NORMAL: FontWeight = FontWeight(400.0);
1009 pub const MEDIUM: FontWeight = FontWeight(500.0);
1011 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1013 pub const BOLD: FontWeight = FontWeight(700.0);
1015 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1017 pub const BLACK: FontWeight = FontWeight(900.0);
1019
1020 pub const ALL: [FontWeight; 9] = [
1022 Self::THIN,
1023 Self::EXTRA_LIGHT,
1024 Self::LIGHT,
1025 Self::NORMAL,
1026 Self::MEDIUM,
1027 Self::SEMIBOLD,
1028 Self::BOLD,
1029 Self::EXTRA_BOLD,
1030 Self::BLACK,
1031 ];
1032}
1033
1034impl schemars::JsonSchema for FontWeight {
1035 fn schema_name() -> std::borrow::Cow<'static, str> {
1036 "FontWeight".into()
1037 }
1038
1039 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1040 use schemars::json_schema;
1041 json_schema!({
1042 "type": "number",
1043 "minimum": Self::THIN,
1044 "maximum": Self::BLACK,
1045 "default": Self::default(),
1046 "description": "Font weight value between 100 (thin) and 900 (black)"
1047 })
1048 }
1049}
1050
1051#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1053pub enum FontStyle {
1054 #[default]
1056 Normal,
1057 Italic,
1059 Oblique,
1061}
1062
1063impl Display for FontStyle {
1064 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1065 Debug::fmt(self, f)
1066 }
1067}
1068
1069#[derive(Clone, Debug, PartialEq, Eq, Default)]
1071pub struct TextRun {
1072 pub len: usize,
1074 pub font: Font,
1076 pub color: Hsla,
1078 pub background_color: Option<Hsla>,
1080 pub underline: Option<UnderlineStyle>,
1082 pub strikethrough: Option<StrikethroughStyle>,
1084}
1085
1086#[cfg(all(target_os = "macos", test))]
1087impl TextRun {
1088 fn with_len(&self, len: usize) -> Self {
1089 let mut this = self.clone();
1090 this.len = len;
1091 this
1092 }
1093}
1094
1095#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1097#[repr(C)]
1098pub struct GlyphId(pub u32);
1099
1100#[derive(Clone, Debug, PartialEq)]
1106#[expect(missing_docs)]
1107pub struct RenderGlyphParams {
1108 pub font_id: FontId,
1109 pub glyph_id: GlyphId,
1110 pub font_size: Pixels,
1111 pub subpixel_variant: Point<u8>,
1112 pub scale_factor: f32,
1113 pub is_emoji: bool,
1114 pub subpixel_rendering: bool,
1115 pub dilation: u8,
1116}
1117
1118impl Eq for RenderGlyphParams {}
1119
1120impl Hash for RenderGlyphParams {
1121 fn hash<H: Hasher>(&self, state: &mut H) {
1122 self.font_id.0.hash(state);
1123 self.glyph_id.0.hash(state);
1124 self.font_size.0.to_bits().hash(state);
1125 self.subpixel_variant.hash(state);
1126 self.scale_factor.to_bits().hash(state);
1127 self.is_emoji.hash(state);
1128 self.subpixel_rendering.hash(state);
1129 self.dilation.hash(state);
1130 }
1131}
1132
1133#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1135pub struct Font {
1136 pub family: SharedString,
1140
1141 pub features: FontFeatures,
1143
1144 pub fallbacks: Option<FontFallbacks>,
1146
1147 pub weight: FontWeight,
1149
1150 pub style: FontStyle,
1152}
1153
1154impl Default for Font {
1155 fn default() -> Self {
1156 font(".SystemUIFont")
1157 }
1158}
1159
1160pub fn font(family: impl Into<SharedString>) -> Font {
1162 Font {
1163 family: family.into(),
1164 features: FontFeatures::default(),
1165 weight: FontWeight::default(),
1166 style: FontStyle::default(),
1167 fallbacks: None,
1168 }
1169}
1170
1171impl Font {
1172 pub fn bold(mut self) -> Self {
1174 self.weight = FontWeight::BOLD;
1175 self
1176 }
1177
1178 pub fn italic(mut self) -> Self {
1180 self.style = FontStyle::Italic;
1181 self
1182 }
1183}
1184
1185#[derive(Clone, Copy, Debug)]
1188pub struct FontMetrics {
1189 pub units_per_em: u32,
1192
1193 pub ascent: f32,
1195
1196 pub descent: f32,
1198
1199 pub line_gap: f32,
1201
1202 pub underline_position: f32,
1204
1205 pub underline_thickness: f32,
1207
1208 pub cap_height: f32,
1210
1211 pub x_height: f32,
1213
1214 pub bounding_box: Bounds<f32>,
1217}
1218
1219impl FontMetrics {
1220 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1222 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1223 }
1224
1225 pub fn descent(&self, font_size: Pixels) -> Pixels {
1227 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1228 }
1229
1230 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1232 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1233 }
1234
1235 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1237 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1238 }
1239
1240 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1242 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1243 }
1244
1245 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1247 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1248 }
1249
1250 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1252 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1253 }
1254
1255 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1257 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1258 }
1259}
1260
1261#[allow(unused)]
1263pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1264 match name {
1268 ".SystemUIFont" => system,
1269 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1270 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1271 _ => name,
1272 }
1273}
1274
1275#[allow(unused)]
1277pub fn font_name_with_fallbacks_shared<'a>(
1278 name: &'a SharedString,
1279 system: &'a SharedString,
1280) -> &'a SharedString {
1281 match name.as_str() {
1285 ".SystemUIFont" => system,
1286 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1287 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1288 _ => name,
1289 }
1290}
1291
1292#[cfg(test)]
1293mod font_resolution_tests {
1294 use super::*;
1295 use crate::NoopTextSystem;
1296
1297 #[test]
1298 fn caches_resolved_font_fallbacks() {
1299 let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));
1300 let requested = font("Missing Font").bold().italic();
1301 let missing = CachedFont::Missing(Arc::new(anyhow::anyhow!("missing font")));
1302 {
1303 let mut font_ids = text_system.font_ids_by_font.write();
1304 font_ids.insert(requested.clone(), missing.clone());
1305 for fallback in &text_system.fallback_font_stack {
1306 font_ids.insert(fallback.clone(), missing.clone());
1307 }
1308 font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));
1309 }
1310
1311 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1312 assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));
1313
1314 text_system.fallback_font_stack.clear();
1315 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1316 }
1317}
1318
1319#[cfg(test)]
1320mod line_wrapper_pool_tests {
1321 use super::*;
1322 use crate::NoopTextSystem;
1323
1324 #[test]
1325 fn pooled_line_wrappers_do_not_retain_text_system() {
1326 let text_system = Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new())));
1327 let weak_text_system = Arc::downgrade(&text_system);
1328
1329 let mut wrapper = text_system.line_wrapper(font(".ZedMono"), px(16.));
1330 let fragments = [LineFragment::text("hello world")];
1331 wrapper
1332 .wrap_line(&fragments, px(40.), IndentAdjustment::default())
1333 .for_each(drop);
1334 drop(wrapper);
1335 drop(text_system);
1336
1337 assert!(weak_text_system.upgrade().is_none());
1338 }
1339}
1340
1341#[cfg(test)]
1342mod missing_glyph_tests {
1343 use super::*;
1344 use futures::FutureExt as _;
1345
1346 #[test]
1347 fn bounds_retained_missing_glyphs() {
1348 let (reporter, mut receiver) = missing_glyph_channel();
1349 reporter.report(
1350 (0..MAX_REPORTED_MISSING_GLYPHS)
1351 .map(|index| {
1352 MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1353 })
1354 .collect(),
1355 );
1356 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1357
1358 let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1359 reporter.report(vec![newest.clone()]);
1360 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1361
1362 let state = &receiver.state;
1363 assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1364 assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1365 assert!(state.reported.contains(&newest));
1366 }
1367
1368 #[test]
1369 fn dropping_receiver_closes_and_clears_reports() {
1370 let (reporter, receiver) = missing_glyph_channel();
1371 reporter.report(vec![missing_glyph("missing")]);
1372
1373 drop(receiver);
1374
1375 assert!(reporter.sender.is_closed());
1376 assert!(reporter.sender.is_empty());
1377 }
1378
1379 fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1380 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1381 let generation = Arc::<AtomicUsize>::default();
1382 let reporter = MissingGlyphReporter {
1383 generation: generation.clone(),
1384 sender,
1385 };
1386 let receiver = MissingGlyphReceiver {
1387 state: MissingGlyphState::default(),
1388 generation,
1389 receiver,
1390 };
1391 (reporter, receiver)
1392 }
1393
1394 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1395 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1396 }
1397}