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 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
433 }
434
435 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
439 Ok(self.advance(font_id, font_size, 'm')?.width)
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(
850 &self,
851 text: &str,
852 font_size: Pixels,
853 runs: &[TextRun],
854 force_width: Option<Pixels>,
855 ) -> Arc<LineLayout> {
856 let mut last_run = None::<&TextRun>;
857 let mut font_runs = self.font_runs_buffer.take();
858 font_runs.clear();
859
860 for run in runs.iter() {
861 let decoration_changed = if let Some(last_run) = last_run
862 && last_run.color == run.color
863 && last_run.underline == run.underline
864 && last_run.strikethrough == run.strikethrough
865 {
868 false
869 } else {
870 last_run = Some(run);
871 true
872 };
873
874 let font_id = self.resolve_font(&run.font);
875 if let Some(font_run) = font_runs.last_mut()
876 && font_id == font_run.font_id
877 && !decoration_changed
878 {
879 font_run.len += run.len;
880 } else {
881 font_runs.push(FontRun {
882 len: run.len,
883 font_id,
884 });
885 }
886 }
887
888 let layout = self.line_layout_cache.layout_line(
889 &SharedString::new(text),
890 font_size,
891 &font_runs,
892 force_width,
893 );
894
895 self.font_runs_buffer.set(font_runs);
896
897 layout
898 }
899
900 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
902 let mut buffer = [0; 4];
903 let buffer: &_ = ch.encode_utf8(&mut buffer);
904 self.line_layout_cache
905 .layout_line(
906 buffer,
907 font_size,
908 &[FontRun {
909 len: buffer.len(),
910 font_id,
911 }],
912 None,
913 )
914 .width
915 }
916
917 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
919 self.layout_width(font_id, font_size, 'm')
920 }
921}
922
923#[derive(Hash, Eq, PartialEq)]
924struct FontIdWithSize {
925 font_id: FontId,
926 font_size: Pixels,
927}
928
929pub struct LineWrapperHandle {
931 wrapper: Option<LineWrapper>,
932 text_system: Arc<TextSystem>,
933}
934
935impl Drop for LineWrapperHandle {
936 fn drop(&mut self) {
937 let mut state = self.text_system.wrapper_pool.lock();
938 let wrapper = self.wrapper.take().unwrap();
939 state
940 .get_mut(&FontIdWithSize {
941 font_id: wrapper.font_id,
942 font_size: wrapper.font_size,
943 })
944 .unwrap()
945 .push(wrapper.into_char_widths());
946 }
947}
948
949impl Deref for LineWrapperHandle {
950 type Target = LineWrapper;
951
952 fn deref(&self) -> &Self::Target {
953 self.wrapper.as_ref().unwrap()
954 }
955}
956
957impl DerefMut for LineWrapperHandle {
958 fn deref_mut(&mut self) -> &mut Self::Target {
959 self.wrapper.as_mut().unwrap()
960 }
961}
962
963#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
966#[serde(transparent)]
967pub struct FontWeight(pub f32);
968
969impl Display for FontWeight {
970 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
971 write!(f, "{}", self.0)
972 }
973}
974
975impl From<f32> for FontWeight {
976 fn from(weight: f32) -> Self {
977 FontWeight(weight)
978 }
979}
980
981impl Default for FontWeight {
982 #[inline]
983 fn default() -> FontWeight {
984 FontWeight::NORMAL
985 }
986}
987
988impl Hash for FontWeight {
989 fn hash<H: Hasher>(&self, state: &mut H) {
990 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
991 }
992}
993
994impl Eq for FontWeight {}
995
996impl FontWeight {
997 pub const THIN: FontWeight = FontWeight(100.0);
999 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1001 pub const LIGHT: FontWeight = FontWeight(300.0);
1003 pub const NORMAL: FontWeight = FontWeight(400.0);
1005 pub const MEDIUM: FontWeight = FontWeight(500.0);
1007 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1009 pub const BOLD: FontWeight = FontWeight(700.0);
1011 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1013 pub const BLACK: FontWeight = FontWeight(900.0);
1015
1016 pub const ALL: [FontWeight; 9] = [
1018 Self::THIN,
1019 Self::EXTRA_LIGHT,
1020 Self::LIGHT,
1021 Self::NORMAL,
1022 Self::MEDIUM,
1023 Self::SEMIBOLD,
1024 Self::BOLD,
1025 Self::EXTRA_BOLD,
1026 Self::BLACK,
1027 ];
1028}
1029
1030impl schemars::JsonSchema for FontWeight {
1031 fn schema_name() -> std::borrow::Cow<'static, str> {
1032 "FontWeight".into()
1033 }
1034
1035 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1036 use schemars::json_schema;
1037 json_schema!({
1038 "type": "number",
1039 "minimum": Self::THIN,
1040 "maximum": Self::BLACK,
1041 "default": Self::default(),
1042 "description": "Font weight value between 100 (thin) and 900 (black)"
1043 })
1044 }
1045}
1046
1047#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1049pub enum FontStyle {
1050 #[default]
1052 Normal,
1053 Italic,
1055 Oblique,
1057}
1058
1059impl Display for FontStyle {
1060 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1061 Debug::fmt(self, f)
1062 }
1063}
1064
1065#[derive(Clone, Debug, PartialEq, Eq, Default)]
1067pub struct TextRun {
1068 pub len: usize,
1070 pub font: Font,
1072 pub color: Hsla,
1074 pub background_color: Option<Hsla>,
1076 pub underline: Option<UnderlineStyle>,
1078 pub strikethrough: Option<StrikethroughStyle>,
1080}
1081
1082#[cfg(all(target_os = "macos", test))]
1083impl TextRun {
1084 fn with_len(&self, len: usize) -> Self {
1085 let mut this = self.clone();
1086 this.len = len;
1087 this
1088 }
1089}
1090
1091#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1093#[repr(C)]
1094pub struct GlyphId(pub u32);
1095
1096#[derive(Clone, Debug, PartialEq)]
1102#[expect(missing_docs)]
1103pub struct RenderGlyphParams {
1104 pub font_id: FontId,
1105 pub glyph_id: GlyphId,
1106 pub font_size: Pixels,
1107 pub subpixel_variant: Point<u8>,
1108 pub scale_factor: f32,
1109 pub is_emoji: bool,
1110 pub subpixel_rendering: bool,
1111 pub dilation: u8,
1112}
1113
1114impl Eq for RenderGlyphParams {}
1115
1116impl Hash for RenderGlyphParams {
1117 fn hash<H: Hasher>(&self, state: &mut H) {
1118 self.font_id.0.hash(state);
1119 self.glyph_id.0.hash(state);
1120 self.font_size.0.to_bits().hash(state);
1121 self.subpixel_variant.hash(state);
1122 self.scale_factor.to_bits().hash(state);
1123 self.is_emoji.hash(state);
1124 self.subpixel_rendering.hash(state);
1125 self.dilation.hash(state);
1126 }
1127}
1128
1129#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1131pub struct Font {
1132 pub family: SharedString,
1136
1137 pub features: FontFeatures,
1139
1140 pub fallbacks: Option<FontFallbacks>,
1142
1143 pub weight: FontWeight,
1145
1146 pub style: FontStyle,
1148}
1149
1150impl Default for Font {
1151 fn default() -> Self {
1152 font(".SystemUIFont")
1153 }
1154}
1155
1156pub fn font(family: impl Into<SharedString>) -> Font {
1158 Font {
1159 family: family.into(),
1160 features: FontFeatures::default(),
1161 weight: FontWeight::default(),
1162 style: FontStyle::default(),
1163 fallbacks: None,
1164 }
1165}
1166
1167impl Font {
1168 pub fn bold(mut self) -> Self {
1170 self.weight = FontWeight::BOLD;
1171 self
1172 }
1173
1174 pub fn italic(mut self) -> Self {
1176 self.style = FontStyle::Italic;
1177 self
1178 }
1179}
1180
1181#[derive(Clone, Copy, Debug)]
1184pub struct FontMetrics {
1185 pub units_per_em: u32,
1188
1189 pub ascent: f32,
1191
1192 pub descent: f32,
1194
1195 pub line_gap: f32,
1197
1198 pub underline_position: f32,
1200
1201 pub underline_thickness: f32,
1203
1204 pub cap_height: f32,
1206
1207 pub x_height: f32,
1209
1210 pub bounding_box: Bounds<f32>,
1213}
1214
1215impl FontMetrics {
1216 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1218 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1219 }
1220
1221 pub fn descent(&self, font_size: Pixels) -> Pixels {
1223 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1224 }
1225
1226 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1228 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1229 }
1230
1231 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1233 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1234 }
1235
1236 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1238 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1239 }
1240
1241 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1243 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1244 }
1245
1246 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1248 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1249 }
1250
1251 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1253 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1254 }
1255}
1256
1257#[allow(unused)]
1259pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1260 match name {
1264 ".SystemUIFont" => system,
1265 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1266 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1267 _ => name,
1268 }
1269}
1270
1271#[allow(unused)]
1273pub fn font_name_with_fallbacks_shared<'a>(
1274 name: &'a SharedString,
1275 system: &'a SharedString,
1276) -> &'a SharedString {
1277 match name.as_str() {
1281 ".SystemUIFont" => system,
1282 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1283 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1284 _ => name,
1285 }
1286}
1287
1288#[cfg(test)]
1289mod font_resolution_tests {
1290 use super::*;
1291 use crate::NoopTextSystem;
1292
1293 #[test]
1294 fn caches_resolved_font_fallbacks() {
1295 let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));
1296 let requested = font("Missing Font").bold().italic();
1297 let missing = CachedFont::Missing(Arc::new(anyhow::anyhow!("missing font")));
1298 {
1299 let mut font_ids = text_system.font_ids_by_font.write();
1300 font_ids.insert(requested.clone(), missing.clone());
1301 for fallback in &text_system.fallback_font_stack {
1302 font_ids.insert(fallback.clone(), missing.clone());
1303 }
1304 font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));
1305 }
1306
1307 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1308 assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));
1309
1310 text_system.fallback_font_stack.clear();
1311 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1312 }
1313}
1314
1315#[cfg(test)]
1316mod line_wrapper_pool_tests {
1317 use super::*;
1318 use crate::NoopTextSystem;
1319
1320 #[test]
1321 fn pooled_line_wrappers_do_not_retain_text_system() {
1322 let text_system = Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new())));
1323 let weak_text_system = Arc::downgrade(&text_system);
1324
1325 let mut wrapper = text_system.line_wrapper(font(".ZedMono"), px(16.));
1326 let fragments = [LineFragment::text("hello world")];
1327 wrapper
1328 .wrap_line(&fragments, px(40.), IndentAdjustment::default())
1329 .for_each(drop);
1330 drop(wrapper);
1331 drop(text_system);
1332
1333 assert!(weak_text_system.upgrade().is_none());
1334 }
1335}
1336
1337#[cfg(test)]
1338mod missing_glyph_tests {
1339 use super::*;
1340 use futures::FutureExt as _;
1341
1342 #[test]
1343 fn bounds_retained_missing_glyphs() {
1344 let (reporter, mut receiver) = missing_glyph_channel();
1345 reporter.report(
1346 (0..MAX_REPORTED_MISSING_GLYPHS)
1347 .map(|index| {
1348 MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1349 })
1350 .collect(),
1351 );
1352 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1353
1354 let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1355 reporter.report(vec![newest.clone()]);
1356 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1357
1358 let state = &receiver.state;
1359 assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1360 assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1361 assert!(state.reported.contains(&newest));
1362 }
1363
1364 #[test]
1365 fn dropping_receiver_closes_and_clears_reports() {
1366 let (reporter, receiver) = missing_glyph_channel();
1367 reporter.report(vec![missing_glyph("missing")]);
1368
1369 drop(receiver);
1370
1371 assert!(reporter.sender.is_closed());
1372 assert!(reporter.sender.is_empty());
1373 }
1374
1375 fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1376 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1377 let generation = Arc::<AtomicUsize>::default();
1378 let reporter = MissingGlyphReporter {
1379 generation: generation.clone(),
1380 sender,
1381 };
1382 let receiver = MissingGlyphReceiver {
1383 state: MissingGlyphState::default(),
1384 generation,
1385 receiver,
1386 };
1387 (reporter, receiver)
1388 }
1389
1390 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1391 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1392 }
1393}