From 47c5617740a3e86ccafd9d7008fb3afb6ff7fbf8 Mon Sep 17 00:00:00 2001 From: Lucas Meurer Date: Tue, 30 Sep 2025 10:12:56 +0200 Subject: [PATCH] Return `0.0` if font not found in `glyph_width` instead of panic (#7559) --- crates/epaint/src/text/font.rs | 11 +++++------ crates/epaint/src/text/fonts.rs | 11 +++++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/crates/epaint/src/text/font.rs b/crates/epaint/src/text/font.rs index c452eb4b..82fd1aab 100644 --- a/crates/epaint/src/text/font.rs +++ b/crates/epaint/src/text/font.rs @@ -478,12 +478,11 @@ impl Font<'_> { /// Width of this character in points. pub fn glyph_width(&mut self, c: char, font_size: f32) -> f32 { let (key, glyph_info) = self.glyph_info(c); - let font = &self - .fonts_by_id - .get(&key) - .expect("Nonexistent font ID") - .ab_glyph_font; - glyph_info.advance_width_unscaled.0 * font.px_scale_factor(font_size) + if let Some(font) = &self.fonts_by_id.get(&key) { + glyph_info.advance_width_unscaled.0 * font.ab_glyph_font.px_scale_factor(font_size) + } else { + 0.0 + } } /// Can we display this glyph? diff --git a/crates/epaint/src/text/fonts.rs b/crates/epaint/src/text/fonts.rs index a78242fd..3efcbe8e 100644 --- a/crates/epaint/src/text/fonts.rs +++ b/crates/epaint/src/text/fonts.rs @@ -651,6 +651,8 @@ impl FontsView<'_> { } /// Width of this character in points. + /// + /// If the font doesn't exist, this will return `0.0`. pub fn glyph_width(&mut self, font_id: &FontId, c: char) -> f32 { self.fonts .font(&font_id.family) @@ -1302,4 +1304,13 @@ mod tests { } } } + + #[test] + fn test_fallback_glyph_width() { + let mut fonts = Fonts::new(1024, AlphaFromCoverage::default(), FontDefinitions::empty()); + let mut view = fonts.with_pixels_per_point(1.0); + + let width = view.glyph_width(&FontId::new(12.0, FontFamily::Proportional), ' '); + assert_eq!(width, 0.0); + } }