Skip to main content

gpui_engine/
text_system.rs

1//! The text-shaping, wrapping, and line-layout surface the authoring layer drives.
2//!
3//! [`PlatformTextSystem`] is the lower-level shaping SPI; [`TextSystem`] adds the
4//! engine's font-resolution, metric, wrapping, and per-frame line-layout caching
5//! on top of it. `gpui_engine_default` ships the standard implementation.
6
7use anyhow::Result;
8use gpui_shared_string::SharedString;
9use gpui_types::{Bounds, DevicePixels, Hsla, Pixels, Size};
10use std::any::Any;
11use std::borrow::Cow;
12use std::future::Future;
13use std::ops::Range;
14use std::pin::Pin;
15use std::sync::Arc;
16
17use crate::{
18    Font, FontId, FontRun, LineLayout, LineLayoutIndex, LineWrapperHandle, MissingGlyph,
19    PlatformTextSystem, RenderGlyphParams, TextRenderingMode, WrappedLineLayout,
20};
21
22/// A stream of grapheme clusters that exhausted font fallback.
23pub trait MissingGlyphReports: Send {
24    /// Waits for the next batch of missing glyphs, or `None` once reporting stops.
25    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Option<Vec<MissingGlyph>>> + Send + '_>>;
26}
27
28/// The text shaping, metric, wrapping, and line-layout surface.
29///
30/// Implementations wrap a [`PlatformTextSystem`] with the engine's font-id,
31/// metric, raster-bounds, and line-wrapper pools, and with the per-frame
32/// line-layout cache the authoring layer reuses.
33pub trait TextSystem: Send + Sync + Any {
34    /// The platform text system this engine wraps.
35    fn platform_text_system(&self) -> &Arc<dyn PlatformTextSystem>;
36
37    /// All font names known to the text system, including fallbacks.
38    fn all_font_names(&self) -> Vec<String>;
39
40    /// Add font data to the text system.
41    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
42
43    /// Takes the receiver for missing-glyph reports.
44    ///
45    /// Only one receiver is available for each text system. Returns `None` when
46    /// the receiver was already taken or another caller is taking it.
47    fn take_missing_glyph_receiver(&self) -> Option<Box<dyn MissingGlyphReports>>;
48
49    /// Starts reporting grapheme clusters that exhaust font fallback.
50    fn enable_missing_glyph_reporting(&self);
51
52    /// Stops reporting missing glyphs and discards any reports collected so far.
53    fn disable_missing_glyph_reporting(&self);
54
55    /// The font for a font id, if it was resolved through this system.
56    fn get_font_for_id(&self, id: FontId) -> Option<Font>;
57
58    /// Resolve a font to its id, falling back to the default stack.
59    fn resolve_font(&self, font: &Font) -> FontId;
60
61    /// Prewarm any system font caches needed to shape text.
62    fn prewarm_fonts(&self, fonts: &[Font]);
63
64    /// The bounding box for a font, at a size.
65    fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels>;
66
67    /// The typographic bounds for a character, in a font and size.
68    fn typographic_bounds(
69        &self,
70        font_id: FontId,
71        font_size: Pixels,
72        character: char,
73    ) -> Result<Bounds<Pixels>>;
74
75    /// The advance width for a character, in a font and size.
76    fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>>;
77
78    /// The shaped layout width of a character, in a font and size.
79    fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels;
80
81    /// The width of an em, in a font and size.
82    fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels>;
83
84    /// The advance width of an em, in a font and size.
85    fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels>;
86
87    /// The width of the `0` character, in a font and size.
88    fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels>;
89
90    /// The advance width of the `0` character, in a font and size.
91    fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels>;
92
93    /// The number of font units per em square.
94    fn units_per_em(&self, font_id: FontId) -> u32;
95
96    /// The cap height of a font, at a size.
97    fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels;
98
99    /// The x-height of a font, at a size.
100    fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels;
101
102    /// The ascent of a font, at a size.
103    fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels;
104
105    /// The descent of a font, at a size.
106    fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels;
107
108    /// The recommended baseline offset for a font, size, and line height.
109    fn baseline_offset(&self, font_id: FontId, font_size: Pixels, line_height: Pixels) -> Pixels;
110
111    /// Take a pooled font-run buffer, or an empty one when the pool is dry.
112    fn take_font_runs(&self) -> Vec<FontRun>;
113
114    /// Return a font-run buffer to the pool for reuse.
115    fn recycle_font_runs(&self, font_runs: Vec<FontRun>);
116
117    /// A line wrapper for the given font and size, returned from a pool.
118    fn line_wrapper(self: Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle;
119
120    /// The rasterized size and location of a glyph.
121    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
122
123    /// Rasterize a glyph, returning its size and coverage bitmap.
124    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
125
126    /// The dilation level to use for a glyph painted in the given color.
127    fn glyph_dilation_for_color(&self, color: Hsla) -> u8;
128
129    /// The rendering mode recommended for a font and size.
130    fn recommended_rendering_mode(&self, font_id: FontId, font_size: Pixels) -> TextRenderingMode;
131
132    /// Saves the current cache position so it can be reused or truncated later.
133    fn layout_index(&self) -> LineLayoutIndex;
134
135    /// Re-inserts layouts from the previous frame created before `range`.
136    fn reuse_layouts(&self, range: Range<LineLayoutIndex>);
137
138    /// Drops layouts created after `index`.
139    fn truncate_layouts(&self, index: LineLayoutIndex);
140
141    /// Ages the current frame's layouts into the previous frame.
142    fn finish_frame(&self);
143
144    /// Shapes and wraps `text`, reusing a cached layout when the inputs match.
145    fn layout_wrapped_line(
146        &self,
147        text: &str,
148        font_size: Pixels,
149        runs: &[FontRun],
150        wrap_width: Option<Pixels>,
151        max_lines: Option<usize>,
152    ) -> Arc<WrappedLineLayout>;
153
154    /// Shapes a single line of `text`, reusing a cached layout when the inputs match.
155    fn layout_line(
156        &self,
157        text: &str,
158        font_size: Pixels,
159        runs: &[FontRun],
160        force_width: Option<Pixels>,
161    ) -> Arc<LineLayout>;
162
163    /// Probe the line-layout cache using a caller-provided content hash.
164    fn try_layout_line_by_hash(
165        &self,
166        text_hash: u64,
167        text_len: usize,
168        font_size: Pixels,
169        runs: &[FontRun],
170        force_width: Option<Pixels>,
171    ) -> Option<Arc<LineLayout>>;
172
173    /// Layout a line using a caller-provided content hash as the cache key.
174    fn layout_line_by_hash(
175        &self,
176        text_hash: u64,
177        text_len: usize,
178        font_size: Pixels,
179        runs: &[FontRun],
180        force_width: Option<Pixels>,
181        materialize_text: Box<dyn FnOnce() -> SharedString>,
182    ) -> Arc<LineLayout>;
183}
184
185impl dyn TextSystem {
186    /// A type-erased view of this text system, for downcasting to a concrete
187    /// implementation (e.g. `ParleyTextSystem`) when a caller needs
188    /// implementation-specific layout features that the shared SPI does not
189    /// expose.
190    pub fn as_any(&self) -> &dyn Any {
191        self as &dyn Any
192    }
193}