1use 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
17const PADDING: f64 = 2.0;
19
20struct Drawn {
22 rgba: Vec<u8>,
24 width: u32,
25 height: u32,
26
27 left: f64,
29
30 ascent: f64,
32
33 advance: f64,
35}
36
37struct CanvasGlyphs {
38 canvas: HtmlCanvasElement,
39 context: CanvasRenderingContext2d,
40
41 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 let white = self.draw(cluster, &font, "white", *subpixel_offset_px)?;
90
91 if self.is_tofu(&white, &font, *subpixel_offset_px) {
92 return None; }
94
95 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 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 fn is_tofu(&mut self, drawn: &Drawn, font: &str, subpixel_offset_px: f32) -> bool {
127 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 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 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 self.context
180 .fill_text(
181 text,
182 PADDING + left + subpixel_offset_px as f64,
183 PADDING + ascent,
184 )
185 .ok()?;
186
187 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
210fn 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; }
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 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}