From ab13f253bdad5b81662563d4e99c951ec3dbc411 Mon Sep 17 00:00:00 2001 From: lucasmerlin Date: Tue, 23 Sep 2025 16:06:07 +0200 Subject: [PATCH 1/2] Return 0.0 if font not found in glyph_width --- crates/epaint/src/text/font.rs | 15 +++++++++------ crates/epaint/src/text/fonts.rs | 11 +++++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/epaint/src/text/font.rs b/crates/epaint/src/text/font.rs index c452eb4bcb6..063ff1e3403 100644 --- a/crates/epaint/src/text/font.rs +++ b/crates/epaint/src/text/font.rs @@ -478,12 +478,15 @@ 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 { + debug_assert_eq!( + glyph_info.advance_width_unscaled.0, 0.0, + "We had no font, so this should be the zero-width fallback glyph" + ); + 0.0 + } } /// Can we display this glyph? diff --git a/crates/epaint/src/text/fonts.rs b/crates/epaint/src/text/fonts.rs index a78242fd41f..3efcbe8ea47 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); + } } From ea53e8c3264f5566dd0bf0866c3904e68acbc75b Mon Sep 17 00:00:00 2001 From: lucasmerlin Date: Tue, 30 Sep 2025 09:50:37 +0200 Subject: [PATCH 2/2] Remove debug assert --- crates/epaint/src/text/font.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/crates/epaint/src/text/font.rs b/crates/epaint/src/text/font.rs index 063ff1e3403..82fd1aab052 100644 --- a/crates/epaint/src/text/font.rs +++ b/crates/epaint/src/text/font.rs @@ -481,10 +481,6 @@ impl Font<'_> { 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 { - debug_assert_eq!( - glyph_info.advance_width_unscaled.0, 0.0, - "We had no font, so this should be the zero-width fallback glyph" - ); 0.0 } }