skathi-gpui 0.4.0

gpui, Zed's GPU-accelerated UI framework, as Skathi renders with it
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
use crate::{
    AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size,
    swap_rgba_pa_to_bgra,
};
use collections::HashMap;
use image::Frame;
use parking_lot::Mutex;
use resvg::tiny_skia::Pixmap;
use smallvec::SmallVec;
use std::{
    hash::Hash,
    path::Path,
    sync::{Arc, LazyLock, OnceLock},
};

#[cfg(target_os = "macos")]
const EMOJI_FONT_FAMILIES: &[&str] = &["Apple Color Emoji", ".AppleColorEmojiUI"];

#[cfg(target_os = "windows")]
const EMOJI_FONT_FAMILIES: &[&str] = &["Segoe UI Emoji", "Segoe UI Symbol"];

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
const EMOJI_FONT_FAMILIES: &[&str] = &[
    "Noto Color Emoji",
    "Emoji One",
    "Twitter Color Emoji",
    "JoyPixels",
];

#[cfg(not(any(
    target_os = "macos",
    target_os = "windows",
    target_os = "linux",
    target_os = "freebsd",
)))]
const EMOJI_FONT_FAMILIES: &[&str] = &[];

fn is_emoji_presentation(c: char) -> bool {
    icu_properties::CodePointSetData::new::<icu_properties::props::EmojiPresentation>().contains(c)
}

fn font_has_char(db: &usvg::fontdb::Database, id: usvg::fontdb::ID, ch: char) -> bool {
    db.with_face_data(id, |font_data, face_index| {
        ttf_parser::Face::parse(font_data, face_index)
            .ok()
            .and_then(|face| face.glyph_index(ch))
            .is_some()
    })
    .unwrap_or(false)
}

fn select_emoji_font(
    ch: char,
    fonts: &[usvg::fontdb::ID],
    db: &usvg::fontdb::Database,
    families: &[&str],
) -> Option<usvg::fontdb::ID> {
    for family_name in families {
        let query = usvg::fontdb::Query {
            families: &[usvg::fontdb::Family::Name(family_name)],
            weight: usvg::fontdb::Weight(400),
            stretch: usvg::fontdb::Stretch::Normal,
            style: usvg::fontdb::Style::Normal,
        };

        let Some(id) = db.query(&query) else {
            continue;
        };

        if fonts.contains(&id) || !font_has_char(db, id, ch) {
            continue;
        }

        return Some(id);
    }

    None
}

/// When rendering SVGs, we render them at twice the size to get a higher-quality result.
pub const SMOOTH_SVG_SCALE_FACTOR: f32 = 2.;

#[derive(Clone, PartialEq, Hash, Eq)]
#[expect(missing_docs)]
pub struct RenderSvgParams {
    pub path: SharedString,
    pub size: Size<DevicePixels>,
}

#[derive(Clone)]
/// A struct holding everything necessary to render SVGs.
pub struct SvgRenderer {
    asset_source: Arc<dyn AssetSource>,
    usvg_options: Arc<usvg::Options<'static>>,
}

/// A parsed SVG document that can be rasterized at any scale.
///
/// Produced by [`SvgRenderer::parse_svg`] and rasterized by
/// [`SvgRenderer::render_parsed`]. Parsing resolves fonts and converts text
/// to paths, so callers that need to rasterize the same SVG at multiple
/// scales should retain this value to avoid re-paying the parse cost.
pub struct ParsedSvg(usvg::Tree);

/// The font of an SVG `<text>` element, as the values of its presentation attributes.
#[derive(Clone, Copy, Debug)]
pub struct SvgTextFont<'a> {
    /// The `font-family` list.
    pub family: &'a str,
    /// The `font-size`, in pixels.
    pub size: f32,
    /// The `font-weight`.
    pub weight: &'a str,
    /// The `font-style`.
    pub style: &'a str,
}

/// The size in which to rasterize the SVG.
#[derive(Clone, Copy)]
pub enum SvgSize {
    /// A width in device pixels. The SVG retains its aspect ratio.
    Size(Size<DevicePixels>),
    /// An exact width and height in device pixels.
    ExactSize(Size<DevicePixels>),
    /// A logical scaling factor to apply to the size provided by the SVG.
    ScaleFactor(f32),
}

impl From<f32> for SvgSize {
    fn from(scale_factor: f32) -> Self {
        Self::ScaleFactor(scale_factor)
    }
}

impl SvgRenderer {
    /// Creates a new SVG renderer with the provided asset source.
    pub fn new(asset_source: Arc<dyn AssetSource>) -> Self {
        static SYSTEM_FONT_DB: LazyLock<Arc<usvg::fontdb::Database>> = LazyLock::new(|| {
            let mut db = usvg::fontdb::Database::new();
            db.load_system_fonts();
            Arc::new(db)
        });

        // Build the enriched font DB lazily on first SVG render rather than
        // eagerly at construction time. This avoids the expensive deep-clone
        // of the system font database for code paths that never render SVGs
        // (e.g. tests).
        let enriched_fontdb = Arc::new(OnceLock::<Mutex<FontDatabase>>::new());

        let default_font_resolver = usvg::FontResolver::default_font_selector();
        let font_resolver = Box::new({
            let asset_source = asset_source.clone();
            let enriched_fontdb = enriched_fontdb.clone();
            move |font: &usvg::Font, db: &mut Arc<usvg::fontdb::Database>| {
                let fontdb = enriched_fontdb.get_or_init(|| {
                    let mut db = (**SYSTEM_FONT_DB).clone();
                    load_bundled_fonts(&*asset_source, &mut db);
                    fix_generic_font_families(&mut db);
                    Mutex::new(FontDatabase {
                        database: Arc::new(db),
                        owned_faces: HashMap::default(),
                        remaining_owned_bytes: MAX_OWNED_FONT_BYTES,
                        fallback_faces: HashMap::default(),
                    })
                });
                if db.is_empty() {
                    *db = fontdb.lock().database.clone();
                }
                let id = default_font_resolver(font, db).or_else(|| {
                    // fontdb doesn't recognize CSS system font keywords like "system-ui"
                    // or "ui-sans-serif", so fall back to sans-serif before any face.
                    let sans_query = usvg::fontdb::Query {
                        families: &[usvg::fontdb::Family::SansSerif],
                        ..Default::default()
                    };
                    db.query(&sans_query)
                        .or_else(|| db.faces().next().map(|f| f.id))
                })?;
                Some(fontdb.lock().owned_face(db, id))
            }
        });
        let default_fallback_selection = usvg::FontResolver::default_fallback_selector();
        let fallback_selection = Box::new(
            move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc<usvg::fontdb::Database>| {
                let mut select = |fonts: &[usvg::fontdb::ID]| {
                    if is_emoji_presentation(ch) {
                        if let Some(id) =
                            select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES)
                        {
                            return Some(id);
                        }
                    }

                    default_fallback_selection(ch, fonts, db)
                };
                let Some(fontdb) = enriched_fontdb.get() else {
                    return select(fonts);
                };
                let face = cached_fallback_face(fontdb, ch, fonts, select)?;
                let owned_face = fontdb.lock().owned_face(db, face);
                Some(if fonts.contains(&owned_face) {
                    face
                } else {
                    owned_face
                })
            },
        );
        let options = usvg::Options {
            font_resolver: usvg::FontResolver {
                select_font: font_resolver,
                select_fallback: fallback_selection,
            },
            ..Default::default()
        };
        Self {
            asset_source,
            usvg_options: Arc::new(options),
        }
    }

    /// Parses SVG data into a [`ParsedSvg`] that can be rasterized at any scale.
    pub fn parse_svg(&self, bytes: &[u8]) -> Result<ParsedSvg, usvg::Error> {
        usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg)
    }

    /// Returns the advance of `text` drawn by this renderer as a single line of SVG `<text>`.
    pub fn measure_text_width(
        &self,
        text: &str,
        font: &SvgTextFont<'_>,
    ) -> Result<f32, usvg::Error> {
        let mut svg = String::from(
            r#"<svg xmlns="http://www.w3.org/2000/svg"><text xml:space="preserve" text-decoration="underline" font-family=""#,
        );
        push_xml_escaped(&mut svg, font.family);
        svg.push_str(r#"" font-weight=""#);
        push_xml_escaped(&mut svg, font.weight);
        svg.push_str(r#"" font-style=""#);
        push_xml_escaped(&mut svg, font.style);
        let size = font.size;
        svg.push_str(&format!(r#"" font-size="{size}">"#));
        push_xml_escaped(&mut svg, text);
        svg.push_str("</text></svg>");

        let tree = usvg::Tree::from_str(&svg, &self.usvg_options)?;
        Ok(underline_width(tree.root()))
    }

    /// Rasterizes a previously parsed SVG into an image buffer.
    pub fn render_parsed(
        &self,
        svg: &ParsedSvg,
        size: impl Into<SvgSize>,
    ) -> Result<Arc<RenderImage>, usvg::Error> {
        let (size, image_scale_factor) = match size.into() {
            SvgSize::Size(size) => (SvgSize::Size(size), 1.0),
            SvgSize::ExactSize(size) => (SvgSize::ExactSize(size), 1.0),
            SvgSize::ScaleFactor(scale_factor) => (
                SvgSize::ScaleFactor(scale_factor * SMOOTH_SVG_SCALE_FACTOR),
                SMOOTH_SVG_SCALE_FACTOR,
            ),
        };
        let pixmap = rasterize_tree(&svg.0, size)?;
        let mut buffer =
            image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take()).unwrap();

        for pixel in buffer.chunks_exact_mut(4) {
            swap_rgba_pa_to_bgra(pixel);
        }

        let mut image = RenderImage::new(SmallVec::from_const([Frame::new(buffer)]));
        image.scale_factor = image_scale_factor;
        Ok(Arc::new(image))
    }

    /// Renders the given bytes into an image buffer.
    pub fn render_single_frame(
        &self,
        bytes: &[u8],
        scale_factor: f32,
    ) -> Result<Arc<RenderImage>, usvg::Error> {
        let svg = self.parse_svg(bytes)?;
        self.render_parsed(&svg, scale_factor)
    }

    pub(crate) fn render_alpha_mask(
        &self,
        params: &RenderSvgParams,
        bytes: Option<&[u8]>,
    ) -> Result<Option<(Size<DevicePixels>, Vec<u8>)>> {
        anyhow::ensure!(!params.size.is_zero(), "can't render at a zero size");

        let render_pixmap = |bytes| {
            let pixmap = self.render_pixmap(bytes, SvgSize::Size(params.size))?;

            // Convert the pixmap's pixels into an alpha mask.
            let size = Size::new(
                DevicePixels(pixmap.width() as i32),
                DevicePixels(pixmap.height() as i32),
            );
            let alpha_mask = pixmap
                .pixels()
                .iter()
                .map(|p| p.alpha())
                .collect::<Vec<_>>();

            Ok(Some((size, alpha_mask)))
        };

        if let Some(bytes) = bytes {
            render_pixmap(bytes)
        } else if let Some(bytes) = self.asset_source.load(&params.path)? {
            render_pixmap(&bytes)
        } else {
            Ok(None)
        }
    }

    fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {
        let tree = usvg::Tree::from_data(bytes, &self.usvg_options)?;
        rasterize_tree(&tree, size)
    }
}

fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result<Pixmap, usvg::Error> {
    // Cap the size of the rendered pixmap to avoid texture allocation panics
    // Related issue: #56466
    const MAX_SIZE: f32 = 8192.0;

    let svg_size = tree.size();
    let (mut width, mut height) = match size {
        SvgSize::Size(size) => {
            let scale = i32::from(size.width) as f32 / svg_size.width();
            (svg_size.width() * scale, svg_size.height() * scale)
        }
        SvgSize::ExactSize(size) => (i32::from(size.width) as f32, i32::from(size.height) as f32),
        SvgSize::ScaleFactor(scale) => (svg_size.width() * scale, svg_size.height() * scale),
    };

    if width > MAX_SIZE {
        log::warn!("Attempted to render pixmap where width ({width}) > MAX_SIZE ({MAX_SIZE})");
    }
    if height > MAX_SIZE {
        log::warn!("Attempted to render pixmap where height ({height}) > MAX_SIZE ({MAX_SIZE})");
    }
    let scale = (MAX_SIZE / width).min(MAX_SIZE / height).min(1.0);
    width *= scale;
    height *= scale;

    // Render the SVG to a pixmap with the specified width and height.
    let mut pixmap = resvg::tiny_skia::Pixmap::new(width as u32, height as u32)
        .ok_or(usvg::Error::InvalidSize)?;

    let transform = resvg::tiny_skia::Transform::from_scale(
        width / svg_size.width(),
        height / svg_size.height(),
    );

    resvg::render(tree, transform, &mut pixmap.as_mut());

    Ok(pixmap)
}

const MAX_OWNED_FONT_BYTES: u64 = 64 * 1024 * 1024;

struct FontDatabase {
    database: Arc<usvg::fontdb::Database>,
    owned_faces: HashMap<usvg::fontdb::ID, usvg::fontdb::ID>,
    remaining_owned_bytes: u64,
    fallback_faces: HashMap<(usvg::fontdb::ID, char), Option<usvg::fontdb::ID>>,
}

impl FontDatabase {
    fn owned_face(
        &mut self,
        db: &mut Arc<usvg::fontdb::Database>,
        id: usvg::fontdb::ID,
    ) -> usvg::fontdb::ID {
        let Some(usvg::fontdb::Source::File(path)) = db.face(id).map(|face| face.source.clone())
        else {
            return id;
        };
        if !self.owned_faces.contains_key(&id) {
            self.own_font_file(&path);
        }
        *db = self.database.clone();
        self.owned_faces.get(&id).copied().unwrap_or(id)
    }

    fn own_font_file(&mut self, path: &Path) {
        let file_faces = self
            .database
            .faces()
            .filter(|face| {
                matches!(&face.source, usvg::fontdb::Source::File(face_path) if face_path == path)
            })
            .map(|face| (face.id, face.index))
            .collect::<Vec<_>>();
        let remaining_owned_bytes = self.remaining_owned_bytes;
        let data = std::fs::metadata(path).and_then(|metadata| {
            (metadata.len() <= remaining_owned_bytes)
                .then(|| std::fs::read(path))
                .transpose()
        });
        let owned_ids = match data {
            Ok(Some(data)) if data.len() as u64 <= remaining_owned_bytes => {
                let size = data.len() as u64;
                let owned_ids = Arc::make_mut(&mut self.database)
                    .load_font_source(usvg::fontdb::Source::Binary(Arc::new(data)));
                if !owned_ids.is_empty() {
                    self.remaining_owned_bytes -= size;
                }
                owned_ids
            }
            Ok(_) => Default::default(),
            Err(error) => {
                log::warn!("Failed to read font {path:?}: {error}");
                Default::default()
            }
        };
        for (id, index) in file_faces {
            let owned_id = owned_ids
                .iter()
                .copied()
                .find(|owned_id| {
                    self.database
                        .face(*owned_id)
                        .is_some_and(|face| face.index == index)
                })
                .unwrap_or(id);
            self.owned_faces.insert(id, owned_id);
        }
    }
}

const MAX_CACHED_FALLBACK_FACES: usize = 16 * 1024;

fn cached_fallback_face(
    fontdb: &Mutex<FontDatabase>,
    ch: char,
    fonts: &[usvg::fontdb::ID],
    mut select: impl FnMut(&[usvg::fontdb::ID]) -> Option<usvg::fontdb::ID>,
) -> Option<usvg::fontdb::ID> {
    let Some(base) = fonts.first() else {
        return select(fonts);
    };
    let key = (*base, ch);
    let cached_face = fontdb.lock().fallback_faces.get(&key).copied();
    let face = match cached_face {
        Some(face) => face,
        None => {
            let face = select(&fonts[..1]);
            let fallback_faces = &mut fontdb.lock().fallback_faces;
            if fallback_faces.len() < MAX_CACHED_FALLBACK_FACES {
                fallback_faces.insert(key, face);
            }
            face
        }
    };
    match face {
        Some(face) if fonts.contains(&face) => select(fonts),
        face => face,
    }
}

fn underline_width(group: &usvg::Group) -> f32 {
    group.children().iter().fold(0., |width, node| {
        width
            + match node {
                usvg::Node::Text(text) => text
                    .layouted()
                    .iter()
                    .filter_map(|span| span.underline.as_ref())
                    .fold(0., |width, underline| {
                        width + underline.data().bounds().width()
                    }),
                usvg::Node::Group(group) => underline_width(group),
                usvg::Node::Path(_) | usvg::Node::Image(_) => 0.,
            }
    })
}

fn push_xml_escaped(xml: &mut String, text: &str) {
    for character in text.chars() {
        match character {
            '&' => xml.push_str("&amp;"),
            '<' => xml.push_str("&lt;"),
            '>' => xml.push_str("&gt;"),
            '"' => xml.push_str("&quot;"),
            '\t' | '\n' | '\r' => xml.push(character),
            '\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {}
            _ => xml.push(character),
        }
    }
}

fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) {
    let font_paths = [
        "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf",
        "fonts/lilex/Lilex-Regular.ttf",
    ];
    for path in font_paths {
        match asset_source.load(path) {
            Ok(Some(data)) => db.load_font_data(data.into_owned()),
            Ok(None) => log::warn!("Bundled font not found: {path}"),
            Err(error) => log::warn!("Failed to load bundled font {path}: {error}"),
        }
    }
}

// fontdb defaults generic families to Microsoft fonts ("Arial", "Times New Roman")
// which aren't installed on most Linux systems. fontconfig normally overrides these,
// but when it fails the defaults remain and all generic family queries return None.
fn fix_generic_font_families(db: &mut usvg::fontdb::Database) {
    use usvg::fontdb::{Family, Query};

    let families_and_fallbacks: &[(Family<'_>, &str)] = &[
        (Family::SansSerif, "IBM Plex Sans"),
        // No serif font bundled; use sans-serif as best available fallback.
        (Family::Serif, "IBM Plex Sans"),
        (Family::Monospace, "Lilex"),
        (Family::Cursive, "IBM Plex Sans"),
        (Family::Fantasy, "IBM Plex Sans"),
    ];

    for (family, fallback_name) in families_and_fallbacks {
        let query = Query {
            families: &[*family],
            ..Default::default()
        };
        if db.query(&query).is_none() {
            match family {
                Family::SansSerif => db.set_sans_serif_family(*fallback_name),
                Family::Serif => db.set_serif_family(*fallback_name),
                Family::Monospace => db.set_monospace_family(*fallback_name),
                Family::Cursive => db.set_cursive_family(*fallback_name),
                Family::Fantasy => db.set_fantasy_family(*fallback_name),
                _ => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{borrow::Cow, cell::Cell};
    use usvg::fontdb::{Database, Family, Query};

    const IBM_PLEX_REGULAR: &[u8] =
        include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
    const LILEX_REGULAR: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf");

    #[test]
    fn renders_parsed_svg_at_requested_size() -> Result<()> {
        let renderer = SvgRenderer::new(Arc::new(()));
        let svg = renderer.parse_svg(
            br#"<svg xmlns="http://www.w3.org/2000/svg" width="24pt" height="12pt"></svg>"#,
        )?;
        let requested_size = Size::new(DevicePixels(24), DevicePixels(12));
        let image = renderer.render_parsed(&svg, SvgSize::ExactSize(requested_size))?;

        assert_eq!(image.size(0), requested_size);
        Ok(())
    }

    #[test]
    fn preserves_aspect_ratio_for_width_constrained_size() -> Result<()> {
        let renderer = SvgRenderer::new(Arc::new(()));
        let svg = renderer.parse_svg(
            br#"<svg xmlns="http://www.w3.org/2000/svg" width="24pt" height="12pt"></svg>"#,
        )?;
        let image = renderer.render_parsed(
            &svg,
            SvgSize::Size(Size::new(DevicePixels(24), DevicePixels(24))),
        )?;

        assert_eq!(image.size(0), Size::new(DevicePixels(24), DevicePixels(12)));
        Ok(())
    }

    #[test]
    fn measured_text_width_matches_rasterized_advance() -> Result<()> {
        let renderer = SvgRenderer::new(Arc::new(BundledFonts));
        let font = SvgTextFont {
            family: "IBM Plex Sans",
            size: 40.,
            weight: "normal",
            style: "normal",
        };
        let frame_width = rasterized_text_width(&renderer, "MM")?;
        assert!(frame_width > 0.);

        for text in ["MMMM", " ", "   ", "\u{a0}", "\u{200b}", "M\u{200b}"] {
            let measured = renderer.measure_text_width(text, &font)?;
            let rasterized = rasterized_text_width(&renderer, &format!("M{text}M"))? - frame_width;
            assert!(
                (measured - rasterized).abs() <= 1.,
                "{text:?} measured {measured}px, rasterized {rasterized}px"
            );
        }
        assert_eq!(
            renderer.measure_text_width("M\u{200b}", &font)?,
            renderer.measure_text_width("M", &font)?
        );
        assert!(renderer.measure_text_width("<&\"\u{1}>", &font)? > 0.);
        Ok(())
    }

    #[test]
    fn owns_font_bytes_within_budget() -> Result<()> {
        let font_path = |name| {
            std::env::temp_dir().join(format!(
                "gpui-svg-renderer-{}-{name}.ttf",
                std::process::id()
            ))
        };
        let (plex_path, lilex_path) = (font_path("plex"), font_path("lilex"));
        std::fs::write(&plex_path, IBM_PLEX_REGULAR)?;
        std::fs::write(&lilex_path, LILEX_REGULAR)?;
        let mut database = Database::new();
        database.load_font_file(&plex_path)?;
        database.load_font_file(&lilex_path)?;
        let mut fonts = FontDatabase {
            database: Arc::new(database),
            owned_faces: HashMap::default(),
            remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64,
            fallback_faces: HashMap::default(),
        };
        let mut db = fonts.database.clone();
        let face_ids = db.faces().map(|face| face.id).collect::<Vec<_>>();
        let (plex_id, lilex_id) = (face_ids[0], face_ids[1]);

        let owned_plex_id = fonts.owned_face(&mut db, plex_id);
        let owned_lilex_id = fonts.owned_face(&mut db, lilex_id);
        std::fs::write(&plex_path, b"changed")?;
        let data_len = |id| db.with_face_data(id, |data, _| data.len());
        let data_lens = (data_len(plex_id), data_len(owned_plex_id));
        std::fs::remove_file(&plex_path)?;
        std::fs::remove_file(&lilex_path)?;

        assert_eq!(data_lens, (Some(7), Some(IBM_PLEX_REGULAR.len())));
        assert_eq!(owned_lilex_id, lilex_id);
        assert_eq!(fonts.remaining_owned_bytes, 0);
        assert_eq!(fonts.owned_face(&mut db, plex_id), owned_plex_id);
        Ok(())
    }

    #[test]
    fn fallback_faces_are_remembered_until_excluded() {
        let database = db_with_bundled_fonts();
        let face_ids = database.faces().map(|face| face.id).collect::<Vec<_>>();
        let (base, fallback) = (face_ids[0], face_ids[1]);
        let fontdb = Mutex::new(FontDatabase {
            database: Arc::new(database),
            owned_faces: HashMap::default(),
            remaining_owned_bytes: 0,
            fallback_faces: HashMap::default(),
        });
        let selections = Cell::new(0);
        let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| {
            cached_fallback_face(&fontdb, ch, fonts, |excluded| {
                selections.set(selections.get() + 1);
                (!excluded.contains(&fallback)).then_some(fallback)
            })
        };

        assert_eq!(fallback_face('x', &[base]), Some(fallback));
        assert_eq!(fallback_face('x', &[base]), Some(fallback));
        assert_eq!(selections.get(), 1);
        assert_eq!(fallback_face('x', &[base, fallback]), None);
        assert_eq!(selections.get(), 2);
        assert_eq!(fallback_face('y', &[base, fallback]), None);
        assert_eq!(selections.get(), 4);
        assert_eq!(fallback_face('y', &[base]), Some(fallback));
        assert_eq!(selections.get(), 4);
    }

    fn db_with_bundled_fonts() -> Database {
        let mut db = Database::new();
        db.load_font_data(IBM_PLEX_REGULAR.to_vec());
        db.load_font_data(LILEX_REGULAR.to_vec());
        db
    }

    #[test]
    fn text_with_split_glyph_clusters_in_mixed_fonts_does_not_panic() {
        let mut db = Database::new();
        db.load_font_data(IBM_PLEX_REGULAR.to_vec());
        db.load_font_data(LILEX_REGULAR.to_vec());
        let options = usvg::Options {
            fontdb: std::sync::Arc::new(db),
            ..Default::default()
        };

        // A base letter followed by a stack of combining marks. Under HarfBuzz's
        // default cluster merging every mark glyph shares the base's byte index,
        // which is the "glyph splitting" condition that triggered the panic. The
        // chunk must use two different fonts so the buggy merge path runs.
        let zalgo = "e\u{0301}\u{0302}\u{0303}\u{0304}\u{0306}\u{0307}\u{0308}\u{030a}";
        let svg = format!(
            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>"#
        );

        // Before the fix this aborts via panic with a message like
        // "removal index (is 5) should be < len (is 5)".
        usvg::Tree::from_data(svg.as_bytes(), &options)
            .expect("SVG with mixed-font text should parse");
    }

    #[test]
    fn test_is_emoji_presentation() {
        let cases = [
            ("a", false),
            ("Z", false),
            ("1", false),
            ("#", false),
            ("*", false),
            ("漢", false),
            ("中", false),
            ("カ", false),
            ("©", false),
            ("♥", false),
            ("😀", true),
            ("✅", true),
            ("🇺🇸", true),
            // SVG fallback is not cluster-aware yet
            ("©️", false),
            ("♥️", false),
            ("1️⃣", false),
        ];
        for (s, expected) in cases {
            assert_eq!(
                is_emoji_presentation(s.chars().next().unwrap()),
                expected,
                "for char {:?}",
                s
            );
        }
    }

    #[test]
    fn fix_generic_font_families_sets_all_families() {
        let mut db = db_with_bundled_fonts();
        fix_generic_font_families(&mut db);

        let families = [
            Family::SansSerif,
            Family::Serif,
            Family::Monospace,
            Family::Cursive,
            Family::Fantasy,
        ];

        for family in families {
            let query = Query {
                families: &[family],
                ..Default::default()
            };
            assert!(
                db.query(&query).is_some(),
                "Expected generic family {family:?} to resolve after fix_generic_font_families"
            );
        }
    }

    #[test]
    fn test_select_emoji_font_skips_family_without_glyph() {
        let db = db_with_bundled_fonts();

        let ibm_plex_sans = db
            .query(&usvg::fontdb::Query {
                families: &[usvg::fontdb::Family::Name("IBM Plex Sans")],
                weight: usvg::fontdb::Weight(400),
                stretch: usvg::fontdb::Stretch::Normal,
                style: usvg::fontdb::Style::Normal,
            })
            .unwrap();
        let lilex = db
            .query(&usvg::fontdb::Query {
                families: &[usvg::fontdb::Family::Name("Lilex")],
                weight: usvg::fontdb::Weight(400),
                stretch: usvg::fontdb::Stretch::Normal,
                style: usvg::fontdb::Style::Normal,
            })
            .unwrap();
        let selected = select_emoji_font('│', &[], &db, &["IBM Plex Sans", "Lilex"]).unwrap();

        assert_eq!(selected, lilex);
        assert!(!font_has_char(&db, ibm_plex_sans, '│'));
        assert!(font_has_char(&db, selected, '│'));
    }

    #[test]
    fn fix_generic_font_families_monospace_resolves_to_lilex() {
        let mut db = db_with_bundled_fonts();
        fix_generic_font_families(&mut db);

        let query = Query {
            families: &[Family::Monospace],
            ..Default::default()
        };
        let id = db.query(&query).expect("Monospace should resolve");
        let face = db.face(id).expect("Face should exist");
        assert!(
            face.families.iter().any(|(name, _)| name.contains("Lilex")),
            "Monospace should map to Lilex, got {:?}",
            face.families
        );
    }

    struct BundledFonts;

    impl AssetSource for BundledFonts {
        fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
            Ok(match path {
                "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf" => {
                    Some(Cow::Borrowed(IBM_PLEX_REGULAR))
                }
                "fonts/lilex/Lilex-Regular.ttf" => Some(Cow::Borrowed(LILEX_REGULAR)),
                _ => None,
            })
        }

        fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
            Ok(Vec::new())
        }
    }

    fn rasterized_text_width(renderer: &SvgRenderer, text: &str) -> Result<f32> {
        let svg = format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="60"><text xml:space="preserve" x="10" y="45" font-family="IBM Plex Sans" font-size="40">{text}</text></svg>"#
        );
        let pixmap = renderer.render_pixmap(svg.as_bytes(), SvgSize::ScaleFactor(1.))?;
        let width = pixmap.width() as usize;
        let inked_columns = (0..width)
            .filter(|column| {
                pixmap
                    .pixels()
                    .iter()
                    .skip(*column)
                    .step_by(width)
                    .any(|pixel| pixel.alpha() > 0)
            })
            .collect::<Vec<_>>();
        Ok(match (inked_columns.first(), inked_columns.last()) {
            (Some(first), Some(last)) => (last - first + 1) as f32,
            _ => 0.,
        })
    }
}