Skip to main content

eframe/web/
canvas_glyphs.rs

1//! Browser glyph rasterization for egui's unsupported-glyph fallback.
2//!
3//! This draws unsupported grapheme clusters with Canvas 2D, then puts the resulting pixels in
4//! egui's font atlas. Clusters the browser cannot render either (tofu) are rejected,
5//! so egui draws its own replacement glyph.
6
7use core::cell::RefCell;
8use std::collections::HashMap;
9
10use egui::{
11    ColorImage, GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE,
12    RasterizedGlyph, has_emoji_presentation, vec2,
13};
14use wasm_bindgen::JsCast as _;
15use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};
16
17/// Room for anti-aliased pixels at the glyph bounds, in physical pixels.
18const PADDING: f64 = 2.0;
19
20/// Result of drawing some text on the canvas.
21struct Drawn {
22    /// Straight (unpremultiplied) RGBA.
23    rgba: Vec<u8>,
24    width: u32,
25    height: u32,
26
27    /// Distance from the pen to the left edge of the ink.
28    left: f64,
29
30    /// Distance from the baseline to the top of the ink.
31    ascent: f64,
32
33    /// Horizontal advance.
34    advance: f64,
35}
36
37struct CanvasGlyphs {
38    canvas: HtmlCanvasElement,
39    context: CanvasRenderingContext2d,
40
41    /// What the browser draws for a missing glyph, per `(font, subpixel offset)`.
42    ///
43    /// `None` if the browser draws nothing.
44    tofu_cache: HashMap<(String, u32), Option<Drawn>>,
45}
46
47impl CanvasGlyphs {
48    fn new() -> Option<Self> {
49        let document = web_sys::window()?.document()?;
50        let canvas = document
51            .create_element("canvas")
52            .ok()?
53            .dyn_into::<HtmlCanvasElement>()
54            .ok()?;
55        let context = canvas
56            .get_context("2d")
57            .ok()??
58            .dyn_into::<CanvasRenderingContext2d>()
59            .ok()?;
60        Some(Self {
61            canvas,
62            context,
63            tofu_cache: Default::default(),
64        })
65    }
66
67    fn rasterize(&mut self, request: &GlyphRasterizerRequest<'_>) -> Option<RasterizedGlyph> {
68        let GlyphRasterizerRequest {
69            cluster,
70            family,
71            font_size_px,
72            subpixel_offset_px,
73        } = request;
74
75        if cluster.trim().is_empty() || !font_size_px.is_finite() || *font_size_px <= 0.0 {
76            return None;
77        }
78
79        let family = match family {
80            egui::FontFamily::Monospace => "monospace",
81            _ => {
82                "system-ui, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Noto Color Emoji\""
83            }
84        };
85        let font = format!("{font_size_px}px {family}");
86
87        // White, like egui's own glyph rasterizer: the atlas stores coverage,
88        // and the tessellator multiplies it with the text color.
89        let white = self.draw(cluster, &font, "white", *subpixel_offset_px)?;
90
91        if self.is_tofu(&white, &font, *subpixel_offset_px) {
92            return None; // Let egui draw its own replacement glyph instead.
93        }
94
95        // Is this a monochrome glyph (to be tinted by the text color) or a color emoji (not)?
96        // Monochrome glyphs take the fill color, color glyphs ignore it,
97        // so we draw twice and see if the fill color made a difference.
98        let black = self.draw(cluster, &font, "black", *subpixel_offset_px)?;
99        let is_color = is_color(cluster, &white, &black);
100
101        let Drawn {
102            rgba,
103            width,
104            height,
105            left,
106            ascent,
107            advance,
108        } = white;
109
110        Some(RasterizedGlyph {
111            bitmap: GlyphBitmap {
112                image: ColorImage::from_rgba_unmultiplied([width as _, height as _], &rgba),
113                // The pen sits at `(PADDING + left, PADDING + ascent)` in the image,
114                // so the image's top-left is this far from the pen:
115                offset_px: vec2(-(left + PADDING) as f32, -(ascent + PADDING) as f32),
116                is_color,
117            },
118            advance_px: advance as f32,
119        })
120    }
121
122    /// Did the browser draw its "missing glyph" box (tofu)?
123    ///
124    /// Browsers draw a box for glyphs they lack, and `measureText` reports
125    /// a width for it, so the only way to tell is to compare pixels.
126    fn is_tofu(&mut self, drawn: &Drawn, font: &str, subpixel_offset_px: f32) -> bool {
127        /// An unassigned code point, so no font has a glyph for it.
128        const MISSING_GLYPH: &str = "\u{0378}";
129
130        let key = (font.to_owned(), subpixel_offset_px.to_bits());
131        if !self.tofu_cache.contains_key(&key) {
132            let tofu = self.draw(MISSING_GLYPH, font, "white", subpixel_offset_px);
133            self.tofu_cache.insert(key.clone(), tofu);
134        }
135
136        self.tofu_cache
137            .get(&key)
138            .and_then(Option::as_ref)
139            .is_some_and(|tofu| {
140                tofu.width == drawn.width && tofu.height == drawn.height && tofu.rgba == drawn.rgba
141            })
142    }
143
144    /// Draw `text` with the given CSS `font` and `fill_style` and read back the pixels.
145    fn draw(
146        &self,
147        text: &str,
148        font: &str,
149        fill_style: &str,
150        subpixel_offset_px: f32,
151    ) -> Option<Drawn> {
152        self.context.set_font(font);
153        self.context.set_text_baseline("alphabetic");
154        let metrics = self.context.measure_text(text).ok()?;
155        let left = metrics.actual_bounding_box_left();
156        let ascent = metrics.actual_bounding_box_ascent();
157        let right = metrics.actual_bounding_box_right();
158        let descent = metrics.actual_bounding_box_descent();
159
160        let width = (left + right + 2.0 * PADDING).ceil().max(1.0) as u32;
161        let height = (ascent + descent + 2.0 * PADDING).ceil().max(1.0) as u32;
162        if MAX_GLYPH_SIZE < width as usize || MAX_GLYPH_SIZE < height as usize {
163            return None;
164        }
165
166        // Only grow: resizing reallocates the backing store and resets all canvas state.
167        if self.canvas.width() < width {
168            self.canvas.set_width(width);
169        }
170        if self.canvas.height() < height {
171            self.canvas.set_height(height);
172        }
173        self.context
174            .clear_rect(0.0, 0.0, width as f64, height as f64);
175        self.context.set_font(font);
176        self.context.set_text_baseline("alphabetic");
177        self.context.set_fill_style_str(fill_style);
178        // Canvas positions text by its baseline, while the image starts at its top-left.
179        self.context
180            .fill_text(
181                text,
182                PADDING + left + subpixel_offset_px as f64,
183                PADDING + ascent,
184            )
185            .ok()?;
186
187        // `web-sys` changes the signature of `get_image_data` based on `web_sys_unstable_apis`,
188        // so we need to call it differently depending on that cfg.
189        let image_data = cfg_select! {
190            web_sys_unstable_apis => self
191            .context
192            .get_image_data(0, 0, width as i32, height as i32),
193            _ => self
194            .context
195            .get_image_data(0.0, 0.0, width as f64, height as f64),
196        };
197        let rgba = image_data.ok()?.data().0;
198
199        Some(Drawn {
200            rgba,
201            width,
202            height,
203            left,
204            ascent,
205            advance: metrics.width(),
206        })
207    }
208}
209
210/// Did the fill color affect the pixels?
211///
212/// Compares a `white` and a `black` draw of the same cluster, pixel by pixel.
213/// A monochrome glyph takes the fill color, so its pixels differ between the two.
214/// A color glyph (emoji) ignores it, so its pixels stay the same.
215///
216/// This is a majority vote rather than an exact comparison:
217/// some browsers (e.g. Firefox for Android) are not pixel-exact between two draws,
218/// and some color glyphs have layers that take the fill color.
219/// Unicode emoji presentation breaks ties, e.g. for glyphs with no opaque pixels.
220///
221/// Looking at the pixels of a single draw does not work:
222/// a black-and-white emoji (⚫, 🖤) looks monochrome but must not be tinted,
223/// and some platforms draw e.g. Thai and Korean with colored (subpixel-antialiased) fringes.
224fn is_color(cluster: &str, white: &Drawn, black: &Drawn) -> bool {
225    let mut monochrome_votes = 0_usize;
226    let mut color_votes = 0_usize;
227
228    for (&[white_r, white_g, white_b, white_a], &[black_r, black_g, black_b, black_a]) in
229        core::iter::zip(white.rgba.as_chunks::<4>().0, black.rgba.as_chunks::<4>().0)
230    {
231        if white_a < 255 || black_a < 255 {
232            continue; // let's only count opaque pixels
233        }
234        let diff_r = white_r.abs_diff(black_r);
235        let diff_g = white_g.abs_diff(black_g);
236        let diff_b = white_b.abs_diff(black_b);
237        let max_diff = diff_r.max(diff_g).max(diff_b);
238        let similar = max_diff < 128;
239
240        if similar {
241            color_votes += 1;
242        } else {
243            monochrome_votes += 1;
244        }
245    }
246
247    if monochrome_votes == color_votes {
248        has_emoji_presentation(cluster)
249    } else {
250        monochrome_votes < color_votes
251    }
252}
253
254thread_local! {
255    // `Context` and `GlyphRasterizer` are `Send + Sync`, but browser Canvas handles are not.
256    // Keeping the handles here lets the callback stay capture-free and usable from `egui::Context`.
257    static CANVAS_GLYPHS: RefCell<Option<CanvasGlyphs>> = const { RefCell::new(None) };
258}
259
260pub(super) fn glyph_rasterizer() -> GlyphRasterizer {
261    GlyphRasterizer::new("eframe::web::canvas_glyphs", |request| {
262        CANVAS_GLYPHS.with(|glyphs| {
263            let mut glyphs = glyphs.borrow_mut();
264            if glyphs.is_none() {
265                *glyphs = CanvasGlyphs::new();
266            }
267            glyphs.as_mut()?.rasterize(request)
268        })
269    })
270}