Skip to main content

epaint/text/
glyph_rasterizer.rs

1use alloc::sync::Arc;
2
3use crate::{
4    ColorImage,
5    text::{FontFamily, FontPriority},
6};
7
8/// Input to a [`GlyphRasterizer`].
9pub struct GlyphRasterizerRequest<'a> {
10    /// The grapheme cluster to rasterize.
11    ///
12    /// For a fallback rasterizer ([`FontPriority::Lowest`]) this is a cluster no installed font has.
13    /// A priority rasterizer ([`FontPriority::Highest`]) is asked about every cluster.
14    pub cluster: &'a str,
15
16    /// The requested font family.
17    pub family: &'a FontFamily,
18
19    /// Requested font size in physical pixels.
20    pub font_size_px: f32,
21
22    /// Horizontal offset from the pixel grid in physical pixels.
23    pub subpixel_offset_px: f32,
24}
25
26/// A glyph bitmap, ready to be copied into the glyph atlas.
27#[derive(Clone)]
28pub struct GlyphBitmap {
29    /// Pixels in physical pixels. Coverage glyphs are white with alpha;
30    /// color glyphs retain their original colors.
31    pub image: ColorImage,
32
33    /// Offset from the glyph origin to the image top-left, in physical pixels.
34    pub offset_px: emath::Vec2,
35
36    /// A color glyph (e.g. emoji) that must not be tinted with the text color.
37    pub is_color: bool,
38}
39
40/// A glyph rasterized by a [`GlyphRasterizer`].
41#[derive(Clone)]
42pub struct RasterizedGlyph {
43    pub bitmap: GlyphBitmap,
44
45    /// Horizontal advance, in physical pixels.
46    pub advance_px: f32,
47}
48
49/// The callback of a [`GlyphRasterizer`].
50type RasterizeFn =
51    dyn for<'a> Fn(&GlyphRasterizerRequest<'a>) -> Option<RasterizedGlyph> + Send + Sync;
52
53/// Rasterizes grapheme clusters using something other than the installed fonts,
54/// e.g. the browser on web, or your own custom glyphs.
55///
56/// By default ([`FontPriority::Lowest`]) a rasterizer is a fallback:
57/// it is only asked about clusters that no installed font can render,
58/// after the [`FontProvider`](crate::text::FontProvider)s have been asked for a font for them.
59///
60/// With [`FontPriority::Highest`] it is instead asked about every cluster,
61/// before any font. Use this to override how specific glyphs look,
62/// e.g. to always render `…` your own way.
63/// Return `None` quickly for everything you do not want to override.
64///
65/// Several rasterizers can be installed. Within a priority tier
66/// they are asked in the order they were added, and the first to return `Some` wins.
67///
68/// Results (and failures) are cached per cluster, family, and size,
69/// so each rasterizer is asked at most once per such combination.
70///
71/// Every rasterizer has a [`Self::key`], which makes installing it idempotent:
72/// adding one when a rasterizer with the same key is already installed is a no-op.
73#[derive(Clone)]
74pub struct GlyphRasterizer {
75    /// Identifies this rasterizer: two rasterizers with the same key are the same rasterizer.
76    ///
77    /// Adding one when a rasterizer with this key is already installed is a no-op,
78    /// so it is safe to add it every frame.
79    /// To swap out an installed rasterizer, replace them all with
80    /// e.g. `Context::set_glyph_rasterizers`.
81    pub key: Arc<str>,
82
83    /// Rasterize one grapheme cluster.
84    ///
85    /// Return `None` if this rasterizer does not handle it.
86    pub rasterize: Arc<RasterizeFn>,
87
88    /// Is this a fallback ([`FontPriority::Lowest`], the default),
89    /// or does it override the installed fonts ([`FontPriority::Highest`])?
90    pub priority: FontPriority,
91}
92
93impl GlyphRasterizer {
94    /// A fallback rasterizer ([`FontPriority::Lowest`]).
95    ///
96    /// `key` identifies the rasterizer (see [`Self::key`]).
97    /// Pick something unique, e.g. a fully qualified name like `"my_crate::MyGlyphs"`.
98    ///
99    /// See [`Self::with_priority`].
100    pub fn new(
101        key: impl Into<Arc<str>>,
102        rasterize: impl for<'a> Fn(&GlyphRasterizerRequest<'a>) -> Option<RasterizedGlyph>
103        + Send
104        + Sync
105        + 'static,
106    ) -> Self {
107        Self {
108            key: key.into(),
109            rasterize: Arc::new(rasterize),
110            priority: FontPriority::Lowest,
111        }
112    }
113
114    /// Should this rasterizer be asked before ([`FontPriority::Highest`])
115    /// or after ([`FontPriority::Lowest`]) the installed fonts?
116    #[inline]
117    pub fn with_priority(mut self, priority: FontPriority) -> Self {
118        self.priority = priority;
119        self
120    }
121
122    /// Add `self` to `rasterizers`, unless one with the same [`Self::key`] is already there.
123    ///
124    /// Returns `true` if it was added.
125    #[doc(hidden)]
126    pub fn insert_into(self, rasterizers: &mut Vec<Self>) -> bool {
127        if rasterizers.iter().any(|r| r.key == self.key) {
128            false
129        } else {
130            rasterizers.push(self);
131            true
132        }
133    }
134}
135
136impl core::fmt::Debug for GlyphRasterizer {
137    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
138        f.debug_struct("GlyphRasterizer")
139            .field("priority", &self.priority)
140            .field("key", &self.key)
141            .finish_non_exhaustive()
142    }
143}
144
145/// Does this grapheme cluster have emoji presentation, per Unicode (UTS #51)?
146///
147/// True for clusters that default to a color glyph (😀, 🦀, 🇸🇪, 👨‍👩‍👧),
148/// for clusters with an explicit emoji presentation selector (⏮️, U+FE0F),
149/// and for emoji modifier (skin tone) sequences (☝🏻).
150///
151/// False for text-presentation symbols (⏮, ✔, ♥) and for clusters
152/// with an explicit text presentation selector (⏮︎, U+FE0E).
153///
154/// Used by `eframe`'s web glyph rasterizer to guess whether a browser-drawn glyph is color.
155pub fn has_emoji_presentation(cluster: &str) -> bool {
156    use unicode_properties::emoji::{
157        EmojiStatus, UnicodeEmoji as _, is_emoji_presentation_selector,
158        is_text_presentation_selector,
159    };
160
161    if cluster.is_ascii() {
162        return false; // Fast path: no ASCII character has emoji presentation.
163    }
164
165    let mut has_emoji_presentation = false;
166    for c in cluster.chars() {
167        if is_text_presentation_selector(c) {
168            return false; // Explicit text presentation wins.
169        }
170        has_emoji_presentation |= is_emoji_presentation_selector(c)
171            || matches!(
172                c.emoji_status(),
173                EmojiStatus::EmojiPresentation
174                    | EmojiStatus::EmojiPresentationAndModifierBase
175                    | EmojiStatus::EmojiPresentationAndEmojiComponent
176                    | EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
177            );
178    }
179    has_emoji_presentation
180}
181
182#[cfg(test)]
183mod has_emoji_presentation_tests {
184    use super::has_emoji_presentation;
185
186    #[test]
187    fn emoji_presentation() {
188        for cluster in [
189            "😀",
190            "🦀",
191            "⏮\u{FE0F}",              // explicit emoji presentation
192            "☝🏻",                     // skin tone modifier sequence
193            "🇸🇪",                     // flag
194            "👨\u{200D}👩\u{200D}👧", // ZWJ sequence
195            "1\u{FE0F}\u{20E3}",      // keycap
196        ] {
197            assert!(has_emoji_presentation(cluster), "{cluster:?}");
198        }
199    }
200
201    #[test]
202    fn text_presentation() {
203        for cluster in [
204            "",
205            "a",
206            "1",
207            "⏮",
208            "⏮\u{FE0E}",  // explicit text presentation
209            "😀\u{FE0E}", // explicit text presentation wins
210            "✔",
211            "♥",
212            "©",
213            "→",
214            "√",
215        ] {
216            assert!(!has_emoji_presentation(cluster), "{cluster:?}");
217        }
218    }
219}