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