1mod font_fallbacks;
2mod font_features;
3mod line;
4mod line_layout;
5mod line_wrapper;
6
7pub use font_fallbacks::*;
8pub use font_features::*;
9pub use line::*;
10pub use line_layout::*;
11pub use line_wrapper::*;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
17 StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
18};
19use anyhow::Context as _;
20use collections::{FxHashMap, FxHashSet};
21use core::fmt;
22use derive_more::{Add, Deref, FromStr, Sub};
23use itertools::Itertools;
24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
25use smallvec::{SmallVec, smallvec};
26use std::{
27 borrow::Cow,
28 cmp,
29 collections::VecDeque,
30 fmt::{Debug, Display, Formatter},
31 hash::{Hash, Hasher},
32 ops::{Deref, DerefMut, Range},
33 sync::{
34 Arc,
35 atomic::{AtomicUsize, Ordering},
36 },
37};
38
39#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
41#[repr(C)]
42pub struct FontId(pub usize);
43
44#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
46pub struct FontFamilyId(pub usize);
47
48pub const SUBPIXEL_VARIANTS_X: u8 = 4;
50
51pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
53
54const UNDERLINE_DESCENT_OFFSET_FACTOR: f32 = 0.618;
56
57pub fn underline_y_offset(line_height: Pixels, ascent: Pixels, descent: Pixels) -> Pixels {
59 let padding_top = (line_height - ascent - descent) / 2.;
60 padding_top + ascent + descent * UNDERLINE_DESCENT_OFFSET_FACTOR
61}
62
63const MAX_REPORTED_MISSING_GLYPHS: usize = 1024;
64
65#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
67pub enum FallbackFontClass {
68 Proportional,
70 Monospace,
72}
73
74#[derive(Clone, Debug, Eq, Hash, PartialEq)]
76pub struct MissingGlyph {
77 grapheme: SharedString,
78 font_class: FallbackFontClass,
79}
80
81impl MissingGlyph {
82 pub fn new(grapheme: SharedString, font_class: FallbackFontClass) -> Self {
84 Self {
85 grapheme,
86 font_class,
87 }
88 }
89
90 pub fn grapheme(&self) -> &str {
92 &self.grapheme
93 }
94
95 pub fn font_class(&self) -> FallbackFontClass {
97 self.font_class
98 }
99}
100
101pub trait MissingGlyphSink: Send + Sync {
103 fn report(&self, missing_glyphs: Vec<MissingGlyph>);
105}
106
107#[derive(Default)]
108struct MissingGlyphState {
109 reported: FxHashSet<MissingGlyph>,
110 reported_order: VecDeque<MissingGlyph>,
111 generation: usize,
112}
113
114impl MissingGlyphState {
115 fn reset(&mut self, generation: usize) {
116 self.reported.clear();
117 self.reported_order.clear();
118 self.generation = generation;
119 }
120}
121
122struct QueuedMissingGlyph {
123 generation: usize,
124 missing_glyph: MissingGlyph,
125}
126
127struct MissingGlyphReporter {
129 generation: Arc<AtomicUsize>,
130 sender: async_channel::Sender<QueuedMissingGlyph>,
131}
132
133impl MissingGlyphSink for MissingGlyphReporter {
134 fn report(&self, missing_glyphs: Vec<MissingGlyph>) {
135 if self.sender.is_closed() {
136 return;
137 }
138
139 let generation = self.generation.load(Ordering::Acquire);
140 for missing_glyph in missing_glyphs.into_iter().unique() {
143 let queued = QueuedMissingGlyph {
144 generation,
145 missing_glyph,
146 };
147 if self.sender.try_send(queued).is_err() {
148 break;
149 }
150 }
151 }
152}
153
154impl MissingGlyphReporter {
155 fn reset(&self) {
156 self.generation.fetch_add(1, Ordering::AcqRel);
157 }
158}
159
160pub(crate) struct MissingGlyphReceiver {
162 state: MissingGlyphState,
163 generation: Arc<AtomicUsize>,
164 receiver: async_channel::Receiver<QueuedMissingGlyph>,
165}
166
167impl MissingGlyphReceiver {
168 pub(crate) async fn recv(
174 &mut self,
175 ) -> std::result::Result<Vec<MissingGlyph>, async_channel::RecvError> {
176 loop {
177 let queued = self.receiver.recv().await?;
178 let mut missing_glyphs = Vec::new();
179 for queued in std::iter::once(queued)
180 .chain(std::iter::from_fn(|| self.receiver.try_recv().ok()))
181 .take(MAX_REPORTED_MISSING_GLYPHS)
182 {
183 let generation = self.generation.load(Ordering::Acquire);
184 if self.state.generation != generation {
185 self.state.reset(generation);
186 missing_glyphs.clear();
187 }
188 if queued.generation != generation
189 || !self.state.reported.insert(queued.missing_glyph.clone())
190 {
191 continue;
192 }
193 self.state
194 .reported_order
195 .push_back(queued.missing_glyph.clone());
196 missing_glyphs.push(queued.missing_glyph);
197 if self.state.reported.len() > MAX_REPORTED_MISSING_GLYPHS
198 && let Some(expired) = self.state.reported_order.pop_front()
199 {
200 self.state.reported.remove(&expired);
201 }
202 }
203 if !missing_glyphs.is_empty() {
204 return Ok(missing_glyphs);
205 }
206 let mut yielded = false;
209 std::future::poll_fn(|cx| {
210 if std::mem::replace(&mut yielded, true) {
211 std::task::Poll::Ready(())
212 } else {
213 cx.waker().wake_by_ref();
214 std::task::Poll::Pending
215 }
216 })
217 .await;
218 }
219 }
220}
221
222impl Drop for MissingGlyphReceiver {
223 fn drop(&mut self) {
224 self.receiver.close();
225 while self.receiver.try_recv().is_ok() {}
226 }
227}
228
229pub struct TextSystem {
231 platform_text_system: Arc<dyn PlatformTextSystem>,
232 font_ids_by_font: RwLock<FxHashMap<Font, CachedFont>>,
233 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
234 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
235 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
236 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
237 fallback_font_stack: SmallVec<[Font; 2]>,
238 font_generation: Arc<AtomicUsize>,
239 missing_glyph_reporter: Arc<MissingGlyphReporter>,
240 missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,
241}
242
243#[derive(Clone)]
244enum CachedFont {
245 Direct(FontId),
246 Fallback(FontId),
247 Missing(Arc<anyhow::Error>),
248}
249
250impl TextSystem {
251 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
253 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
254 let missing_glyph_generation = Arc::<AtomicUsize>::default();
255 TextSystem {
256 platform_text_system,
257 font_metrics: RwLock::default(),
258 raster_bounds: RwLock::default(),
259 font_ids_by_font: RwLock::default(),
260 wrapper_pool: Mutex::default(),
261 font_runs_pool: Mutex::default(),
262 fallback_font_stack: smallvec![
263 font(".ZedMono"),
265 font(".ZedSans"),
266 font("Helvetica"),
267 font("Segoe UI"), font("Ubuntu"), font("Adwaita Sans"), font("Cantarell"), font("Noto Sans"), font("DejaVu Sans"),
273 font("Arial"), ],
275 font_generation: Arc::default(),
276 missing_glyph_reporter: Arc::new(MissingGlyphReporter {
277 generation: missing_glyph_generation.clone(),
278 sender,
279 }),
280 missing_glyph_receiver: Mutex::new(Some(MissingGlyphReceiver {
281 state: MissingGlyphState::default(),
282 generation: missing_glyph_generation,
283 receiver,
284 })),
285 }
286 }
287
288 pub fn all_font_names(&self) -> Vec<String> {
292 let mut names = self.platform_text_system.all_font_names();
293 names.sort_unstable();
294 names.dedup();
295 names
296 }
297
298 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
303 self.platform_text_system.add_fonts(fonts)?;
304 self.font_ids_by_font.write().clear();
305 self.missing_glyph_reporter.reset();
306 self.font_generation.fetch_add(1, Ordering::Release);
307 Ok(())
308 }
309
310 pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
315 self.missing_glyph_receiver
316 .try_lock()
317 .and_then(|mut receiver| receiver.take())
318 }
319
320 pub(crate) fn enable_missing_glyph_reporting(&self) {
321 self.platform_text_system
322 .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
323 }
324
325 pub(crate) fn disable_missing_glyph_reporting(&self) {
326 self.platform_text_system.set_missing_glyph_sink(None);
327 self.missing_glyph_reporter.reset();
328 }
329
330 #[cfg(test)]
331 pub(crate) fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
332 self.missing_glyph_reporter.report(missing_glyphs);
333 }
334
335 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
337 let lock = self.font_ids_by_font.read();
338 lock.iter()
339 .filter_map(|(font, result)| match result {
340 CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),
341 _ => None,
342 })
343 .next()
344 }
345
346 pub fn resolve_font(&self, font: &Font) -> FontId {
353 if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
354 self.font_ids_by_font.read().get(font)
355 {
356 return *font_id;
357 }
358 self.resolve_font_uncached(font)
359 }
360
361 pub fn prewarm_fonts(&self, fonts: &[Font]) {
367 let mut font_ids = SmallVec::<[FontId; 8]>::new();
368 for font in fonts {
369 let font_id = self.resolve_font(font);
370 if !font_ids.contains(&font_id) {
371 font_ids.push(font_id);
372 }
373 }
374 self.platform_text_system.prewarm_fonts(&font_ids);
375 }
376
377 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
381 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
382 }
383
384 pub fn typographic_bounds(
386 &self,
387 font_id: FontId,
388 font_size: Pixels,
389 character: char,
390 ) -> Result<Bounds<Pixels>> {
391 let glyph_id = self
392 .platform_text_system
393 .glyph_for_char(font_id, character)
394 .with_context(|| format!("glyph not found for character '{character}'"))?;
395 let bounds = self
396 .platform_text_system
397 .typographic_bounds(font_id, glyph_id)?;
398 Ok(self.read_metrics(font_id, |metrics| {
399 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
400 }))
401 }
402
403 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
405 let glyph_id = self
406 .platform_text_system
407 .glyph_for_char(font_id, ch)
408 .with_context(|| format!("glyph not found for character '{ch}'"))?;
409 let result = self.platform_text_system.advance(font_id, glyph_id)?
410 / self.units_per_em(font_id) as f32;
411
412 Ok(result * font_size)
413 }
414
415 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
418 let mut buffer = [0; 4];
419 let buffer = ch.encode_utf8(&mut buffer);
420 self.platform_text_system
421 .layout_line(
422 buffer,
423 font_size,
424 &[FontRun {
425 len: buffer.len(),
426 font_id,
427 }],
428 )
429 .width
430 }
431
432 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
436 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
437 }
438
439 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
443 Ok(self.advance(font_id, font_size, 'm')?.width)
444 }
445
446 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
450 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
451 }
452
453 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
457 Ok(self.advance(font_id, font_size, '0')?.width)
458 }
459
460 pub fn units_per_em(&self, font_id: FontId) -> u32 {
464 self.read_metrics(font_id, |metrics| metrics.units_per_em)
465 }
466
467 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
469 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
470 }
471
472 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
474 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
475 }
476
477 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
479 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
480 }
481
482 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
485 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
486 }
487
488 pub fn baseline_offset(
490 &self,
491 font_id: FontId,
492 font_size: Pixels,
493 line_height: Pixels,
494 ) -> Pixels {
495 let ascent = self.ascent(font_id, font_size);
496 let descent = self.descent(font_id, font_size);
497 let padding_top = (line_height - ascent - descent) / 2.;
498 padding_top + ascent
499 }
500
501 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
502 let lock = self.font_metrics.upgradable_read();
503
504 if let Some(metrics) = lock.get(&font_id) {
505 read(metrics)
506 } else {
507 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
508 let metrics = lock
509 .entry(font_id)
510 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
511 read(metrics)
512 }
513 }
514
515 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
517 let lock = &mut self.wrapper_pool.lock();
518 let font_id = self.resolve_font(&font);
519 let wrappers = lock
520 .entry(FontIdWithSize { font_id, font_size })
521 .or_default();
522 let wrapper = wrappers
523 .pop()
524 .unwrap_or_else(|| LineWrapper::new(font_id, font_size, self.clone()));
525
526 LineWrapperHandle {
527 wrapper: Some(wrapper),
528 text_system: self.clone(),
529 }
530 }
531
532 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
534 let raster_bounds = self.raster_bounds.upgradable_read();
535 if let Some(bounds) = raster_bounds.get(params) {
536 Ok(*bounds)
537 } else {
538 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
539 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
540 raster_bounds.insert(params.clone(), bounds);
541 Ok(bounds)
542 }
543 }
544
545 pub(crate) fn rasterize_glyph(
546 &self,
547 params: &RenderGlyphParams,
548 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
549 let raster_bounds = self.raster_bounds(params)?;
550 self.platform_text_system
551 .rasterize_glyph(params, raster_bounds)
552 }
553
554 pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
556 self.platform_text_system.glyph_dilation_for_color(color)
557 }
558
559 pub(crate) fn recommended_rendering_mode(
562 &self,
563 font_id: FontId,
564 font_size: Pixels,
565 ) -> TextRenderingMode {
566 self.platform_text_system
567 .recommended_rendering_mode(font_id, font_size)
568 }
569
570 fn resolve_font_uncached(&self, font: &Font) -> FontId {
571 let mut font_error = None;
572 let font_id = {
573 let mut font_ids = self.font_ids_by_font.upgradable_read();
574 if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
575 font_ids.get(font)
576 {
577 return *font_id;
578 }
579
580 let mut lookup_font = |candidate: &Font| {
581 let cached = if let Some(cached) = font_ids.get(candidate) {
582 cached.clone()
583 } else {
584 let cached = match self.platform_text_system.font_id(candidate) {
585 Ok(font_id) => CachedFont::Direct(font_id),
586 Err(error) => CachedFont::Missing(Arc::new(error)),
587 };
588 font_ids.with_upgraded(|font_ids| {
589 font_ids.insert(candidate.clone(), cached.clone());
590 });
591 cached
592 };
593 match cached {
594 CachedFont::Direct(font_id) => Some(font_id),
595 CachedFont::Fallback(_) => None,
596 CachedFont::Missing(error) => {
597 if candidate == font {
598 font_error = Some(error);
599 }
600 None
601 }
602 }
603 };
604
605 if let Some(font_id) = lookup_font(font) {
606 Some(font_id)
607 } else {
608 let font_id = self.fallback_font_stack.iter().find_map(lookup_font);
609 if let Some(font_id) = font_id {
610 font_ids.with_upgraded(|font_ids| {
611 font_ids.insert(font.clone(), CachedFont::Fallback(font_id));
612 });
613 }
614 font_id
615 }
616 };
617 if let Some(error) = font_error {
618 log::warn!("failed to load font {font:?}: {error:#}");
619 }
620 font_id.unwrap_or_else(|| {
621 panic!(
622 "failed to resolve font '{}' or any of the fallbacks: {}",
623 font.family,
624 self.fallback_font_stack
625 .iter()
626 .map(|fallback| &fallback.family)
627 .join(", ")
628 );
629 })
630 }
631}
632
633#[derive(Deref)]
635pub struct WindowTextSystem {
636 line_layout_cache: LineLayoutCache,
637 #[deref]
638 text_system: Arc<TextSystem>,
639}
640
641impl WindowTextSystem {
642 pub fn new(text_system: Arc<TextSystem>) -> Self {
644 Self {
645 line_layout_cache: LineLayoutCache::new(
646 text_system.platform_text_system.clone(),
647 text_system.font_generation.clone(),
648 ),
649 text_system,
650 }
651 }
652
653 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
654 self.line_layout_cache.layout_index()
655 }
656
657 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
658 self.line_layout_cache.reuse_layouts(index)
659 }
660
661 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
662 self.line_layout_cache.truncate_layouts(index)
663 }
664
665 pub fn shape_line(
672 &self,
673 text: SharedString,
674 font_size: Pixels,
675 runs: &[TextRun],
676 force_width: Option<Pixels>,
677 ) -> ShapedLine {
678 debug_assert!(
679 text.find('\n').is_none(),
680 "text argument should not contain newlines"
681 );
682
683 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
684 for run in runs {
685 if let Some(last_run) = decoration_runs.last_mut()
686 && last_run.color == run.color
687 && last_run.underline == run.underline
688 && last_run.strikethrough == run.strikethrough
689 && last_run.background_color == run.background_color
690 {
691 last_run.len += run.len as u32;
692 continue;
693 }
694 decoration_runs.push(DecorationRun {
695 len: run.len as u32,
696 color: run.color,
697 background_color: run.background_color,
698 underline: run.underline,
699 strikethrough: run.strikethrough,
700 });
701 }
702
703 let layout = self.layout_line(&text, font_size, runs, force_width);
704
705 ShapedLine {
706 layout,
707 text,
708 decoration_runs,
709 }
710 }
711
712 pub fn shape_line_by_hash(
723 &self,
724 text_hash: u64,
725 text_len: usize,
726 font_size: Pixels,
727 runs: &[TextRun],
728 force_width: Option<Pixels>,
729 materialize_text: impl FnOnce() -> SharedString,
730 ) -> ShapedLine {
731 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
732 for run in runs {
733 if let Some(last_run) = decoration_runs.last_mut()
734 && last_run.color == run.color
735 && last_run.underline == run.underline
736 && last_run.strikethrough == run.strikethrough
737 && last_run.background_color == run.background_color
738 {
739 last_run.len += run.len as u32;
740 continue;
741 }
742 decoration_runs.push(DecorationRun {
743 len: run.len as u32,
744 color: run.color,
745 background_color: run.background_color,
746 underline: run.underline,
747 strikethrough: run.strikethrough,
748 });
749 }
750
751 let mut used_force_width = force_width;
752 let layout = self.layout_line_by_hash(
753 text_hash,
754 text_len,
755 font_size,
756 runs,
757 used_force_width,
758 || {
759 let text = materialize_text();
760 debug_assert!(
761 text.find('\n').is_none(),
762 "text argument should not contain newlines"
763 );
764 text
765 },
766 );
767
768 let text: SharedString = SharedString::new_static("");
772
773 ShapedLine {
774 layout,
775 text,
776 decoration_runs,
777 }
778 }
779
780 pub fn shape_text(
784 &self,
785 text: SharedString,
786 font_size: Pixels,
787 runs: &[TextRun],
788 wrap_width: Option<Pixels>,
789 line_clamp: Option<usize>,
790 ) -> Result<SmallVec<[WrappedLine; 1]>> {
791 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
792 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
793
794 let mut lines = SmallVec::new();
795 let mut max_wrap_lines = line_clamp;
796 let mut wrapped_lines = 0;
797
798 let mut process_line = |line_text: SharedString, line_start, line_end| {
799 font_runs.clear();
800
801 let mut decoration_runs = <Vec<DecorationRun>>::with_capacity(32);
802 let mut run_start = line_start;
803 while run_start < line_end {
804 let Some(run) = runs.peek_mut() else {
805 log::warn!("`TextRun`s do not cover the entire to be shaped text");
806 break;
807 };
808
809 let run_len_within_line = cmp::min(line_end - run_start, run.len);
810
811 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
812 && last_run.color == run.color
813 && last_run.underline == run.underline
814 && last_run.strikethrough == run.strikethrough
815 && last_run.background_color == run.background_color
816 {
817 last_run.len += run_len_within_line as u32;
818 false
819 } else {
820 decoration_runs.push(DecorationRun {
821 len: run_len_within_line as u32,
822 color: run.color,
823 background_color: run.background_color,
824 underline: run.underline,
825 strikethrough: run.strikethrough,
826 });
827 true
828 };
829
830 let font_id = self.resolve_font(&run.font);
831 if let Some(font_run) = font_runs.last_mut()
832 && font_id == font_run.font_id
833 && !decoration_changed
834 {
835 font_run.len += run_len_within_line;
836 } else {
837 font_runs.push(FontRun {
838 len: run_len_within_line,
839 font_id,
840 });
841 }
842
843 run.len -= run_len_within_line;
845 if run.len == 0 {
846 runs.next();
847 }
848 run_start += run_len_within_line;
849 }
850
851 let layout = self.line_layout_cache.layout_wrapped_line(
852 &line_text,
853 font_size,
854 &font_runs,
855 wrap_width,
856 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
857 );
858 wrapped_lines += layout.wrap_boundaries.len();
859
860 lines.push(WrappedLine {
861 layout,
862 decoration_runs,
863 text: line_text,
864 });
865
866 if let Some(run) = runs.peek_mut() {
868 run.len -= 1;
869 if run.len == 0 {
870 runs.next();
871 }
872 }
873 };
874
875 let mut split_lines = text.split('\n');
876
877 if let Some(first_line) = split_lines.next()
879 && let Some(second_line) = split_lines.next()
880 {
881 let mut line_start = 0;
882 process_line(
883 SharedString::new(first_line),
884 line_start,
885 line_start + first_line.len(),
886 );
887 line_start += first_line.len() + '\n'.len_utf8();
888 process_line(
889 SharedString::new(second_line),
890 line_start,
891 line_start + second_line.len(),
892 );
893 for line_text in split_lines {
894 line_start += line_text.len() + '\n'.len_utf8();
895 process_line(
896 SharedString::new(line_text),
897 line_start,
898 line_start + line_text.len(),
899 );
900 }
901 } else {
902 let end = text.len();
903 process_line(text, 0, end);
904 }
905
906 self.font_runs_pool.lock().push(font_runs);
907
908 Ok(lines)
909 }
910
911 pub(crate) fn finish_frame(&self) {
912 self.line_layout_cache.finish_frame()
913 }
914
915 pub fn layout_line(
920 &self,
921 text: &str,
922 font_size: Pixels,
923 runs: &[TextRun],
924 force_width: Option<Pixels>,
925 ) -> Arc<LineLayout> {
926 let mut last_run = None::<&TextRun>;
927 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
928 font_runs.clear();
929
930 for run in runs.iter() {
931 let decoration_changed = if let Some(last_run) = last_run
932 && last_run.color == run.color
933 && last_run.underline == run.underline
934 && last_run.strikethrough == run.strikethrough
935 {
938 false
939 } else {
940 last_run = Some(run);
941 true
942 };
943
944 let font_id = self.resolve_font(&run.font);
945 if let Some(font_run) = font_runs.last_mut()
946 && font_id == font_run.font_id
947 && !decoration_changed
948 {
949 font_run.len += run.len;
950 } else {
951 font_runs.push(FontRun {
952 len: run.len,
953 font_id,
954 });
955 }
956 }
957
958 let layout = self.line_layout_cache.layout_line(
959 &SharedString::new(text),
960 font_size,
961 &font_runs,
962 force_width,
963 );
964
965 self.font_runs_pool.lock().push(font_runs);
966
967 layout
968 }
969
970 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
972 let mut buffer = [0; 4];
973 let buffer: &_ = ch.encode_utf8(&mut buffer);
974 self.line_layout_cache
975 .layout_line(
976 buffer,
977 font_size,
978 &[FontRun {
979 len: buffer.len(),
980 font_id,
981 }],
982 None,
983 )
984 .width
985 }
986
987 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
989 self.layout_width(font_id, font_size, 'm')
990 }
991
992 pub fn try_layout_line_by_hash(
1001 &self,
1002 text_hash: u64,
1003 text_len: usize,
1004 font_size: Pixels,
1005 runs: &[TextRun],
1006 force_width: Option<Pixels>,
1007 ) -> Option<Arc<LineLayout>> {
1008 let mut last_run = None::<&TextRun>;
1009 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
1010 font_runs.clear();
1011
1012 for run in runs.iter() {
1013 let decoration_changed = if let Some(last_run) = last_run
1014 && last_run.color == run.color
1015 && last_run.underline == run.underline
1016 && last_run.strikethrough == run.strikethrough
1017 {
1020 false
1021 } else {
1022 last_run = Some(run);
1023 true
1024 };
1025
1026 let font_id = self.resolve_font(&run.font);
1027 if let Some(font_run) = font_runs.last_mut()
1028 && font_id == font_run.font_id
1029 && !decoration_changed
1030 {
1031 font_run.len += run.len;
1032 } else {
1033 font_runs.push(FontRun {
1034 len: run.len,
1035 font_id,
1036 });
1037 }
1038 }
1039
1040 let layout = self.line_layout_cache.try_layout_line_by_hash(
1041 text_hash,
1042 text_len,
1043 font_size,
1044 &font_runs,
1045 force_width,
1046 );
1047
1048 self.font_runs_pool.lock().push(font_runs);
1049
1050 layout
1051 }
1052
1053 pub fn layout_line_by_hash(
1062 &self,
1063 text_hash: u64,
1064 text_len: usize,
1065 font_size: Pixels,
1066 runs: &[TextRun],
1067 force_width: Option<Pixels>,
1068 materialize_text: impl FnOnce() -> SharedString,
1069 ) -> Arc<LineLayout> {
1070 let mut last_run = None::<&TextRun>;
1071 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
1072 font_runs.clear();
1073
1074 for run in runs.iter() {
1075 let decoration_changed = if let Some(last_run) = last_run
1076 && last_run.color == run.color
1077 && last_run.underline == run.underline
1078 && last_run.strikethrough == run.strikethrough
1079 {
1082 false
1083 } else {
1084 last_run = Some(run);
1085 true
1086 };
1087
1088 let font_id = self.resolve_font(&run.font);
1089 if let Some(font_run) = font_runs.last_mut()
1090 && font_id == font_run.font_id
1091 && !decoration_changed
1092 {
1093 font_run.len += run.len;
1094 } else {
1095 font_runs.push(FontRun {
1096 len: run.len,
1097 font_id,
1098 });
1099 }
1100 }
1101
1102 let layout = self.line_layout_cache.layout_line_by_hash(
1103 text_hash,
1104 text_len,
1105 font_size,
1106 &font_runs,
1107 force_width,
1108 materialize_text,
1109 );
1110
1111 self.font_runs_pool.lock().push(font_runs);
1112
1113 layout
1114 }
1115}
1116
1117#[derive(Hash, Eq, PartialEq)]
1118struct FontIdWithSize {
1119 font_id: FontId,
1120 font_size: Pixels,
1121}
1122
1123pub struct LineWrapperHandle {
1125 wrapper: Option<LineWrapper>,
1126 text_system: Arc<TextSystem>,
1127}
1128
1129impl Drop for LineWrapperHandle {
1130 fn drop(&mut self) {
1131 let mut state = self.text_system.wrapper_pool.lock();
1132 let wrapper = self.wrapper.take().unwrap();
1133 state
1134 .get_mut(&FontIdWithSize {
1135 font_id: wrapper.font_id,
1136 font_size: wrapper.font_size,
1137 })
1138 .unwrap()
1139 .push(wrapper);
1140 }
1141}
1142
1143impl Deref for LineWrapperHandle {
1144 type Target = LineWrapper;
1145
1146 fn deref(&self) -> &Self::Target {
1147 self.wrapper.as_ref().unwrap()
1148 }
1149}
1150
1151impl DerefMut for LineWrapperHandle {
1152 fn deref_mut(&mut self) -> &mut Self::Target {
1153 self.wrapper.as_mut().unwrap()
1154 }
1155}
1156
1157#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
1160#[serde(transparent)]
1161pub struct FontWeight(pub f32);
1162
1163impl Display for FontWeight {
1164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1165 write!(f, "{}", self.0)
1166 }
1167}
1168
1169impl From<f32> for FontWeight {
1170 fn from(weight: f32) -> Self {
1171 FontWeight(weight)
1172 }
1173}
1174
1175impl Default for FontWeight {
1176 #[inline]
1177 fn default() -> FontWeight {
1178 FontWeight::NORMAL
1179 }
1180}
1181
1182impl Hash for FontWeight {
1183 fn hash<H: Hasher>(&self, state: &mut H) {
1184 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
1185 }
1186}
1187
1188impl Eq for FontWeight {}
1189
1190impl FontWeight {
1191 pub const THIN: FontWeight = FontWeight(100.0);
1193 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1195 pub const LIGHT: FontWeight = FontWeight(300.0);
1197 pub const NORMAL: FontWeight = FontWeight(400.0);
1199 pub const MEDIUM: FontWeight = FontWeight(500.0);
1201 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1203 pub const BOLD: FontWeight = FontWeight(700.0);
1205 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1207 pub const BLACK: FontWeight = FontWeight(900.0);
1209
1210 pub const ALL: [FontWeight; 9] = [
1212 Self::THIN,
1213 Self::EXTRA_LIGHT,
1214 Self::LIGHT,
1215 Self::NORMAL,
1216 Self::MEDIUM,
1217 Self::SEMIBOLD,
1218 Self::BOLD,
1219 Self::EXTRA_BOLD,
1220 Self::BLACK,
1221 ];
1222}
1223
1224impl schemars::JsonSchema for FontWeight {
1225 fn schema_name() -> std::borrow::Cow<'static, str> {
1226 "FontWeight".into()
1227 }
1228
1229 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1230 use schemars::json_schema;
1231 json_schema!({
1232 "type": "number",
1233 "minimum": Self::THIN,
1234 "maximum": Self::BLACK,
1235 "default": Self::default(),
1236 "description": "Font weight value between 100 (thin) and 900 (black)"
1237 })
1238 }
1239}
1240
1241#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1243pub enum FontStyle {
1244 #[default]
1246 Normal,
1247 Italic,
1249 Oblique,
1251}
1252
1253impl Display for FontStyle {
1254 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1255 Debug::fmt(self, f)
1256 }
1257}
1258
1259#[derive(Clone, Debug, PartialEq, Eq, Default)]
1261pub struct TextRun {
1262 pub len: usize,
1264 pub font: Font,
1266 pub color: Hsla,
1268 pub background_color: Option<Hsla>,
1270 pub underline: Option<UnderlineStyle>,
1272 pub strikethrough: Option<StrikethroughStyle>,
1274}
1275
1276#[cfg(all(target_os = "macos", test))]
1277impl TextRun {
1278 fn with_len(&self, len: usize) -> Self {
1279 let mut this = self.clone();
1280 this.len = len;
1281 this
1282 }
1283}
1284
1285#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1287#[repr(C)]
1288pub struct GlyphId(pub u32);
1289
1290#[derive(Clone, Debug, PartialEq)]
1296#[expect(missing_docs)]
1297pub struct RenderGlyphParams {
1298 pub font_id: FontId,
1299 pub glyph_id: GlyphId,
1300 pub font_size: Pixels,
1301 pub subpixel_variant: Point<u8>,
1302 pub scale_factor: f32,
1303 pub is_emoji: bool,
1304 pub subpixel_rendering: bool,
1305 pub dilation: u8,
1306}
1307
1308impl Eq for RenderGlyphParams {}
1309
1310impl Hash for RenderGlyphParams {
1311 fn hash<H: Hasher>(&self, state: &mut H) {
1312 self.font_id.0.hash(state);
1313 self.glyph_id.0.hash(state);
1314 self.font_size.0.to_bits().hash(state);
1315 self.subpixel_variant.hash(state);
1316 self.scale_factor.to_bits().hash(state);
1317 self.is_emoji.hash(state);
1318 self.subpixel_rendering.hash(state);
1319 self.dilation.hash(state);
1320 }
1321}
1322
1323#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1325pub struct Font {
1326 pub family: SharedString,
1330
1331 pub features: FontFeatures,
1333
1334 pub fallbacks: Option<FontFallbacks>,
1336
1337 pub weight: FontWeight,
1339
1340 pub style: FontStyle,
1342}
1343
1344impl Default for Font {
1345 fn default() -> Self {
1346 font(".SystemUIFont")
1347 }
1348}
1349
1350pub fn font(family: impl Into<SharedString>) -> Font {
1352 Font {
1353 family: family.into(),
1354 features: FontFeatures::default(),
1355 weight: FontWeight::default(),
1356 style: FontStyle::default(),
1357 fallbacks: None,
1358 }
1359}
1360
1361impl Font {
1362 pub fn bold(mut self) -> Self {
1364 self.weight = FontWeight::BOLD;
1365 self
1366 }
1367
1368 pub fn italic(mut self) -> Self {
1370 self.style = FontStyle::Italic;
1371 self
1372 }
1373}
1374
1375#[derive(Clone, Copy, Debug)]
1378pub struct FontMetrics {
1379 pub units_per_em: u32,
1382
1383 pub ascent: f32,
1385
1386 pub descent: f32,
1388
1389 pub line_gap: f32,
1391
1392 pub underline_position: f32,
1394
1395 pub underline_thickness: f32,
1397
1398 pub cap_height: f32,
1400
1401 pub x_height: f32,
1403
1404 pub bounding_box: Bounds<f32>,
1407}
1408
1409impl FontMetrics {
1410 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1412 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1413 }
1414
1415 pub fn descent(&self, font_size: Pixels) -> Pixels {
1417 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1418 }
1419
1420 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1422 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1423 }
1424
1425 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1427 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1428 }
1429
1430 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1432 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1433 }
1434
1435 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1437 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1438 }
1439
1440 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1442 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1443 }
1444
1445 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1447 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1448 }
1449}
1450
1451#[allow(unused)]
1453pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1454 match name {
1458 ".SystemUIFont" => system,
1459 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1460 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1461 _ => name,
1462 }
1463}
1464
1465#[allow(unused)]
1467pub fn font_name_with_fallbacks_shared<'a>(
1468 name: &'a SharedString,
1469 system: &'a SharedString,
1470) -> &'a SharedString {
1471 match name.as_str() {
1475 ".SystemUIFont" => system,
1476 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1477 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1478 _ => name,
1479 }
1480}
1481
1482#[cfg(test)]
1483mod font_resolution_tests {
1484 use super::*;
1485 use crate::NoopTextSystem;
1486
1487 #[test]
1488 fn caches_resolved_font_fallbacks() {
1489 let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));
1490 let requested = font("Missing Font").bold().italic();
1491 let missing = CachedFont::Missing(Arc::new(anyhow::anyhow!("missing font")));
1492 {
1493 let mut font_ids = text_system.font_ids_by_font.write();
1494 font_ids.insert(requested.clone(), missing.clone());
1495 for fallback in &text_system.fallback_font_stack {
1496 font_ids.insert(fallback.clone(), missing.clone());
1497 }
1498 font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));
1499 }
1500
1501 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1502 assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));
1503
1504 text_system.fallback_font_stack.clear();
1505 assert_eq!(text_system.resolve_font(&requested), FontId(42));
1506 }
1507}
1508
1509#[cfg(test)]
1510mod missing_glyph_tests {
1511 use super::*;
1512 use futures::FutureExt as _;
1513
1514 #[test]
1515 fn bounds_retained_missing_glyphs() {
1516 let (reporter, mut receiver) = missing_glyph_channel();
1517 reporter.report(
1518 (0..MAX_REPORTED_MISSING_GLYPHS)
1519 .map(|index| {
1520 MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1521 })
1522 .collect(),
1523 );
1524 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1525
1526 let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1527 reporter.report(vec![newest.clone()]);
1528 assert!(receiver.recv().now_or_never().unwrap().is_ok());
1529
1530 let state = &receiver.state;
1531 assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1532 assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1533 assert!(state.reported.contains(&newest));
1534 }
1535
1536 #[test]
1537 fn dropping_receiver_closes_and_clears_reports() {
1538 let (reporter, receiver) = missing_glyph_channel();
1539 reporter.report(vec![missing_glyph("missing")]);
1540
1541 drop(receiver);
1542
1543 assert!(reporter.sender.is_closed());
1544 assert!(reporter.sender.is_empty());
1545 }
1546
1547 fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1548 let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1549 let generation = Arc::<AtomicUsize>::default();
1550 let reporter = MissingGlyphReporter {
1551 generation: generation.clone(),
1552 sender,
1553 };
1554 let receiver = MissingGlyphReceiver {
1555 state: MissingGlyphState::default(),
1556 generation,
1557 receiver,
1558 };
1559 (reporter, receiver)
1560 }
1561
1562 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1563 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1564 }
1565}