Skip to main content

gpui/
svg_renderer.rs

1use crate::{
2    AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size,
3    swap_rgba_pa_to_bgra,
4};
5use image::Frame;
6use resvg::tiny_skia::Pixmap;
7use smallvec::SmallVec;
8use std::{
9    hash::Hash,
10    sync::{Arc, LazyLock, OnceLock},
11};
12
13#[cfg(target_os = "macos")]
14const EMOJI_FONT_FAMILIES: &[&str] = &["Apple Color Emoji", ".AppleColorEmojiUI"];
15
16#[cfg(target_os = "windows")]
17const EMOJI_FONT_FAMILIES: &[&str] = &["Segoe UI Emoji", "Segoe UI Symbol"];
18
19#[cfg(any(target_os = "linux", target_os = "freebsd"))]
20const EMOJI_FONT_FAMILIES: &[&str] = &[
21    "Noto Color Emoji",
22    "Emoji One",
23    "Twitter Color Emoji",
24    "JoyPixels",
25];
26
27#[cfg(not(any(
28    target_os = "macos",
29    target_os = "windows",
30    target_os = "linux",
31    target_os = "freebsd",
32)))]
33const EMOJI_FONT_FAMILIES: &[&str] = &[];
34
35fn is_emoji_presentation(c: char) -> bool {
36    static EMOJI_PRESENTATION_REGEX: LazyLock<regex::Regex> =
37        LazyLock::new(|| regex::Regex::new("\\p{Emoji_Presentation}").unwrap());
38    let mut buf = [0u8; 4];
39    EMOJI_PRESENTATION_REGEX.is_match(c.encode_utf8(&mut buf))
40}
41
42fn font_has_char(db: &usvg::fontdb::Database, id: usvg::fontdb::ID, ch: char) -> bool {
43    db.with_face_data(id, |font_data, face_index| {
44        ttf_parser::Face::parse(font_data, face_index)
45            .ok()
46            .and_then(|face| face.glyph_index(ch))
47            .is_some()
48    })
49    .unwrap_or(false)
50}
51
52fn select_emoji_font(
53    ch: char,
54    fonts: &[usvg::fontdb::ID],
55    db: &usvg::fontdb::Database,
56    families: &[&str],
57) -> Option<usvg::fontdb::ID> {
58    for family_name in families {
59        let query = usvg::fontdb::Query {
60            families: &[usvg::fontdb::Family::Name(family_name)],
61            weight: usvg::fontdb::Weight(400),
62            stretch: usvg::fontdb::Stretch::Normal,
63            style: usvg::fontdb::Style::Normal,
64        };
65
66        let Some(id) = db.query(&query) else {
67            continue;
68        };
69
70        if fonts.contains(&id) || !font_has_char(db, id, ch) {
71            continue;
72        }
73
74        return Some(id);
75    }
76
77    None
78}
79
80/// When rendering SVGs, we render them at twice the size to get a higher-quality result.
81pub const SMOOTH_SVG_SCALE_FACTOR: f32 = 2.;
82
83#[derive(Clone, PartialEq, Hash, Eq)]
84#[expect(missing_docs)]
85pub struct RenderSvgParams {
86    pub path: SharedString,
87    pub size: Size<DevicePixels>,
88}
89
90#[derive(Clone)]
91/// A struct holding everything necessary to render SVGs.
92pub struct SvgRenderer {
93    asset_source: Arc<dyn AssetSource>,
94    usvg_options: Arc<usvg::Options<'static>>,
95}
96
97/// A parsed SVG document that can be rasterized at any scale.
98///
99/// Produced by [`SvgRenderer::parse_svg`] and rasterized by
100/// [`SvgRenderer::render_parsed`]. Parsing resolves fonts and converts text
101/// to paths, so callers that need to rasterize the same SVG at multiple
102/// scales should retain this value to avoid re-paying the parse cost.
103pub struct ParsedSvg(usvg::Tree);
104
105/// The size in which to rasterize the SVG.
106#[derive(Clone, Copy)]
107pub enum SvgSize {
108    /// A width in device pixels. The SVG retains its aspect ratio.
109    Size(Size<DevicePixels>),
110    /// An exact width and height in device pixels.
111    ExactSize(Size<DevicePixels>),
112    /// A logical scaling factor to apply to the size provided by the SVG.
113    ScaleFactor(f32),
114}
115
116impl From<f32> for SvgSize {
117    fn from(scale_factor: f32) -> Self {
118        Self::ScaleFactor(scale_factor)
119    }
120}
121
122impl SvgRenderer {
123    /// Creates a new SVG renderer with the provided asset source.
124    pub fn new(asset_source: Arc<dyn AssetSource>) -> Self {
125        static SYSTEM_FONT_DB: LazyLock<Arc<usvg::fontdb::Database>> = LazyLock::new(|| {
126            let mut db = usvg::fontdb::Database::new();
127            db.load_system_fonts();
128            Arc::new(db)
129        });
130
131        // Build the enriched font DB lazily on first SVG render rather than
132        // eagerly at construction time. This avoids the expensive deep-clone
133        // of the system font database for code paths that never render SVGs
134        // (e.g. tests).
135        let enriched_fontdb: Arc<OnceLock<Arc<usvg::fontdb::Database>>> = Arc::new(OnceLock::new());
136
137        let default_font_resolver = usvg::FontResolver::default_font_selector();
138        let font_resolver = Box::new({
139            let asset_source = asset_source.clone();
140            move |font: &usvg::Font, db: &mut Arc<usvg::fontdb::Database>| {
141                if db.is_empty() {
142                    let fontdb = enriched_fontdb.get_or_init(|| {
143                        let mut db = (**SYSTEM_FONT_DB).clone();
144                        load_bundled_fonts(&*asset_source, &mut db);
145                        fix_generic_font_families(&mut db);
146                        Arc::new(db)
147                    });
148                    *db = fontdb.clone();
149                }
150                if let Some(id) = default_font_resolver(font, db) {
151                    return Some(id);
152                }
153                // fontdb doesn't recognize CSS system font keywords like "system-ui"
154                // or "ui-sans-serif", so fall back to sans-serif before any face.
155                let sans_query = usvg::fontdb::Query {
156                    families: &[usvg::fontdb::Family::SansSerif],
157                    ..Default::default()
158                };
159                db.query(&sans_query)
160                    .or_else(|| db.faces().next().map(|f| f.id))
161            }
162        });
163        let default_fallback_selection = usvg::FontResolver::default_fallback_selector();
164        let fallback_selection = Box::new(
165            move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc<usvg::fontdb::Database>| {
166                if is_emoji_presentation(ch) {
167                    if let Some(id) = select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES)
168                    {
169                        return Some(id);
170                    }
171                }
172
173                default_fallback_selection(ch, fonts, db)
174            },
175        );
176        let options = usvg::Options {
177            font_resolver: usvg::FontResolver {
178                select_font: font_resolver,
179                select_fallback: fallback_selection,
180            },
181            ..Default::default()
182        };
183        Self {
184            asset_source,
185            usvg_options: Arc::new(options),
186        }
187    }
188
189    /// Parses SVG data into a [`ParsedSvg`] that can be rasterized at any scale.
190    pub fn parse_svg(&self, bytes: &[u8]) -> Result<ParsedSvg, usvg::Error> {
191        usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg)
192    }
193
194    /// Rasterizes a previously parsed SVG into an image buffer.
195    pub fn render_parsed(
196        &self,
197        svg: &ParsedSvg,
198        size: impl Into<SvgSize>,
199    ) -> Result<Arc<RenderImage>, usvg::Error> {
200        let (size, image_scale_factor) = match size.into() {
201            SvgSize::Size(size) => (SvgSize::Size(size), 1.0),
202            SvgSize::ExactSize(size) => (SvgSize::ExactSize(size), 1.0),
203            SvgSize::ScaleFactor(scale_factor) => (
204                SvgSize::ScaleFactor(scale_factor * SMOOTH_SVG_SCALE_FACTOR),
205                SMOOTH_SVG_SCALE_FACTOR,
206            ),
207        };
208        let pixmap = rasterize_tree(&svg.0, size)?;
209        let mut buffer =
210            image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take()).unwrap();
211
212        for pixel in buffer.chunks_exact_mut(4) {
213            swap_rgba_pa_to_bgra(pixel);
214        }
215
216        let mut image = RenderImage::new(SmallVec::from_const([Frame::new(buffer)]));
217        image.scale_factor = image_scale_factor;
218        Ok(Arc::new(image))
219    }
220
221    /// Renders the given bytes into an image buffer.
222    pub fn render_single_frame(
223        &self,
224        bytes: &[u8],
225        scale_factor: f32,
226    ) -> Result<Arc<RenderImage>, usvg::Error> {
227        let svg = self.parse_svg(bytes)?;
228        self.render_parsed(&svg, scale_factor)
229    }
230
231    pub(crate) fn render_alpha_mask(
232        &self,
233        params: &RenderSvgParams,
234        bytes: Option<&[u8]>,
235    ) -> Result<Option<(Size<DevicePixels>, Vec<u8>)>> {
236        anyhow::ensure!(!params.size.is_zero(), "can't render at a zero size");
237
238        let render_pixmap = |bytes| {
239            let pixmap = self.render_pixmap(bytes, SvgSize::Size(params.size))?;
240
241            // Convert the pixmap's pixels into an alpha mask.
242            let size = Size::new(
243                DevicePixels(pixmap.width() as i32),
244                DevicePixels(pixmap.height() as i32),
245            );
246            let alpha_mask = pixmap
247                .pixels()
248                .iter()
249                .map(|p| p.alpha())
250                .collect::<Vec<_>>();
251
252            Ok(Some((size, alpha_mask)))
253        };
254
255        if let Some(bytes) = bytes {
256            render_pixmap(bytes)
257        } else if let Some(bytes) = self.asset_source.load(&params.path)? {
258            render_pixmap(&bytes)
259        } else {
260            Ok(None)
261        }
262    }
263
264    fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {
265        let tree = usvg::Tree::from_data(bytes, &self.usvg_options)?;
266        rasterize_tree(&tree, size)
267    }
268}
269
270fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result<Pixmap, usvg::Error> {
271    // Cap the size of the rendered pixmap to avoid texture allocation panics
272    // Related issue: #56466
273    const MAX_SIZE: f32 = 8192.0;
274
275    let svg_size = tree.size();
276    let (mut width, mut height) = match size {
277        SvgSize::Size(size) => {
278            let scale = i32::from(size.width) as f32 / svg_size.width();
279            (svg_size.width() * scale, svg_size.height() * scale)
280        }
281        SvgSize::ExactSize(size) => (i32::from(size.width) as f32, i32::from(size.height) as f32),
282        SvgSize::ScaleFactor(scale) => (svg_size.width() * scale, svg_size.height() * scale),
283    };
284
285    if width > MAX_SIZE {
286        log::warn!("Attempted to render pixmap where width ({width}) > MAX_SIZE ({MAX_SIZE})");
287    }
288    if height > MAX_SIZE {
289        log::warn!("Attempted to render pixmap where height ({height}) > MAX_SIZE ({MAX_SIZE})");
290    }
291    let scale = (MAX_SIZE / width).min(MAX_SIZE / height).min(1.0);
292    width *= scale;
293    height *= scale;
294
295    // Render the SVG to a pixmap with the specified width and height.
296    let mut pixmap = resvg::tiny_skia::Pixmap::new(width as u32, height as u32)
297        .ok_or(usvg::Error::InvalidSize)?;
298
299    let transform = resvg::tiny_skia::Transform::from_scale(
300        width / svg_size.width(),
301        height / svg_size.height(),
302    );
303
304    resvg::render(tree, transform, &mut pixmap.as_mut());
305
306    Ok(pixmap)
307}
308
309fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) {
310    let font_paths = [
311        "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf",
312        "fonts/lilex/Lilex-Regular.ttf",
313    ];
314    for path in font_paths {
315        match asset_source.load(path) {
316            Ok(Some(data)) => db.load_font_data(data.into_owned()),
317            Ok(None) => log::warn!("Bundled font not found: {path}"),
318            Err(error) => log::warn!("Failed to load bundled font {path}: {error}"),
319        }
320    }
321}
322
323// fontdb defaults generic families to Microsoft fonts ("Arial", "Times New Roman")
324// which aren't installed on most Linux systems. fontconfig normally overrides these,
325// but when it fails the defaults remain and all generic family queries return None.
326fn fix_generic_font_families(db: &mut usvg::fontdb::Database) {
327    use usvg::fontdb::{Family, Query};
328
329    let families_and_fallbacks: &[(Family<'_>, &str)] = &[
330        (Family::SansSerif, "IBM Plex Sans"),
331        // No serif font bundled; use sans-serif as best available fallback.
332        (Family::Serif, "IBM Plex Sans"),
333        (Family::Monospace, "Lilex"),
334        (Family::Cursive, "IBM Plex Sans"),
335        (Family::Fantasy, "IBM Plex Sans"),
336    ];
337
338    for (family, fallback_name) in families_and_fallbacks {
339        let query = Query {
340            families: &[*family],
341            ..Default::default()
342        };
343        if db.query(&query).is_none() {
344            match family {
345                Family::SansSerif => db.set_sans_serif_family(*fallback_name),
346                Family::Serif => db.set_serif_family(*fallback_name),
347                Family::Monospace => db.set_monospace_family(*fallback_name),
348                Family::Cursive => db.set_cursive_family(*fallback_name),
349                Family::Fantasy => db.set_fantasy_family(*fallback_name),
350                _ => {}
351            }
352        }
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use usvg::fontdb::{Database, Family, Query};
360
361    const IBM_PLEX_REGULAR: &[u8] =
362        include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
363    const LILEX_REGULAR: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf");
364
365    #[test]
366    fn renders_parsed_svg_at_requested_size() -> Result<()> {
367        let renderer = SvgRenderer::new(Arc::new(()));
368        let svg = renderer.parse_svg(
369            br#"<svg xmlns="http://www.w3.org/2000/svg" width="24pt" height="12pt"></svg>"#,
370        )?;
371        let requested_size = Size::new(DevicePixels(24), DevicePixels(12));
372        let image = renderer.render_parsed(&svg, SvgSize::ExactSize(requested_size))?;
373
374        assert_eq!(image.size(0), requested_size);
375        Ok(())
376    }
377
378    #[test]
379    fn preserves_aspect_ratio_for_width_constrained_size() -> Result<()> {
380        let renderer = SvgRenderer::new(Arc::new(()));
381        let svg = renderer.parse_svg(
382            br#"<svg xmlns="http://www.w3.org/2000/svg" width="24pt" height="12pt"></svg>"#,
383        )?;
384        let image = renderer.render_parsed(
385            &svg,
386            SvgSize::Size(Size::new(DevicePixels(24), DevicePixels(24))),
387        )?;
388
389        assert_eq!(image.size(0), Size::new(DevicePixels(24), DevicePixels(12)));
390        Ok(())
391    }
392
393    fn db_with_bundled_fonts() -> Database {
394        let mut db = Database::new();
395        db.load_font_data(IBM_PLEX_REGULAR.to_vec());
396        db.load_font_data(LILEX_REGULAR.to_vec());
397        db
398    }
399
400    #[test]
401    fn text_with_split_glyph_clusters_in_mixed_fonts_does_not_panic() {
402        let mut db = Database::new();
403        db.load_font_data(IBM_PLEX_REGULAR.to_vec());
404        db.load_font_data(LILEX_REGULAR.to_vec());
405        let options = usvg::Options {
406            fontdb: std::sync::Arc::new(db),
407            ..Default::default()
408        };
409
410        // A base letter followed by a stack of combining marks. Under HarfBuzz's
411        // default cluster merging every mark glyph shares the base's byte index,
412        // which is the "glyph splitting" condition that triggered the panic. The
413        // chunk must use two different fonts so the buggy merge path runs.
414        let zalgo = "e\u{0301}\u{0302}\u{0303}\u{0304}\u{0306}\u{0307}\u{0308}\u{030a}";
415        let svg = format!(
416            r#"<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><text font-family="Lilex" font-size="32">{zalgo}<tspan font-family="IBM Plex Sans">{zalgo}</tspan></text></svg>"#
417        );
418
419        // Before the fix this aborts via panic with a message like
420        // "removal index (is 5) should be < len (is 5)".
421        usvg::Tree::from_data(svg.as_bytes(), &options)
422            .expect("SVG with mixed-font text should parse");
423    }
424
425    #[test]
426    fn test_is_emoji_presentation() {
427        let cases = [
428            ("a", false),
429            ("Z", false),
430            ("1", false),
431            ("#", false),
432            ("*", false),
433            ("漢", false),
434            ("中", false),
435            ("カ", false),
436            ("©", false),
437            ("♥", false),
438            ("😀", true),
439            ("✅", true),
440            ("🇺🇸", true),
441            // SVG fallback is not cluster-aware yet
442            ("©️", false),
443            ("♥️", false),
444            ("1️⃣", false),
445        ];
446        for (s, expected) in cases {
447            assert_eq!(
448                is_emoji_presentation(s.chars().next().unwrap()),
449                expected,
450                "for char {:?}",
451                s
452            );
453        }
454    }
455
456    #[test]
457    fn fix_generic_font_families_sets_all_families() {
458        let mut db = db_with_bundled_fonts();
459        fix_generic_font_families(&mut db);
460
461        let families = [
462            Family::SansSerif,
463            Family::Serif,
464            Family::Monospace,
465            Family::Cursive,
466            Family::Fantasy,
467        ];
468
469        for family in families {
470            let query = Query {
471                families: &[family],
472                ..Default::default()
473            };
474            assert!(
475                db.query(&query).is_some(),
476                "Expected generic family {family:?} to resolve after fix_generic_font_families"
477            );
478        }
479    }
480
481    #[test]
482    fn test_select_emoji_font_skips_family_without_glyph() {
483        let mut db = db_with_bundled_fonts();
484
485        let ibm_plex_sans = db
486            .query(&usvg::fontdb::Query {
487                families: &[usvg::fontdb::Family::Name("IBM Plex Sans")],
488                weight: usvg::fontdb::Weight(400),
489                stretch: usvg::fontdb::Stretch::Normal,
490                style: usvg::fontdb::Style::Normal,
491            })
492            .unwrap();
493        let lilex = db
494            .query(&usvg::fontdb::Query {
495                families: &[usvg::fontdb::Family::Name("Lilex")],
496                weight: usvg::fontdb::Weight(400),
497                stretch: usvg::fontdb::Stretch::Normal,
498                style: usvg::fontdb::Style::Normal,
499            })
500            .unwrap();
501        let selected = select_emoji_font('│', &[], &db, &["IBM Plex Sans", "Lilex"]).unwrap();
502
503        assert_eq!(selected, lilex);
504        assert!(!font_has_char(&db, ibm_plex_sans, '│'));
505        assert!(font_has_char(&db, selected, '│'));
506    }
507
508    #[test]
509    fn fix_generic_font_families_monospace_resolves_to_lilex() {
510        let mut db = db_with_bundled_fonts();
511        fix_generic_font_families(&mut db);
512
513        let query = Query {
514            families: &[Family::Monospace],
515            ..Default::default()
516        };
517        let id = db.query(&query).expect("Monospace should resolve");
518        let face = db.face(id).expect("Face should exist");
519        assert!(
520            face.families.iter().any(|(name, _)| name.contains("Lilex")),
521            "Monospace should map to Lilex, got {:?}",
522            face.families
523        );
524    }
525}