gpui: Do not panic when unable to find the selected fonts (#42212)

Lukas Wirth created

Fixes ZED-329

Release Notes:

- N/A *or* Added/Fixed/Improved ...

Change summary

crates/gpui/src/platform/windows/direct_write.rs | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)

Detailed changes

crates/gpui/src/platform/windows/direct_write.rs 🔗

@@ -231,7 +231,9 @@ impl PlatformTextSystem for DirectWriteTextSystem {
             Ok(*font_id)
         } else {
             let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
-            let font_id = lock.select_font(font);
+            let font_id = lock
+                .select_font(font)
+                .with_context(|| format!("Failed to select font: {:?}", font))?;
             lock.font_selections.insert(font.clone(), font_id);
             Ok(font_id)
         }
@@ -457,7 +459,7 @@ impl DirectWriteState {
         }
     }
 
-    fn select_font(&mut self, target_font: &Font) -> FontId {
+    fn select_font(&mut self, target_font: &Font) -> Option<FontId> {
         unsafe {
             if target_font.family == ".SystemUIFont" {
                 let family = self.system_ui_font_name.clone();
@@ -468,7 +470,6 @@ impl DirectWriteState {
                     &target_font.features,
                     target_font.fallbacks.as_ref(),
                 )
-                .unwrap()
             } else {
                 let family = self.system_ui_font_name.clone();
                 self.find_font_id(
@@ -478,7 +479,7 @@ impl DirectWriteState {
                     &target_font.features,
                     target_font.fallbacks.as_ref(),
                 )
-                .unwrap_or_else(|| {
+                .or_else(|| {
                     #[cfg(any(test, feature = "test-support"))]
                     {
                         panic!("ERROR: {} font not found!", target_font.family);
@@ -494,7 +495,6 @@ impl DirectWriteState {
                             target_font.fallbacks.as_ref(),
                             true,
                         )
-                        .unwrap()
                     }
                 })
             }
@@ -1472,8 +1472,10 @@ impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
             .get(&font_identifier)
         {
             *id
+        } else if let Some(id) = context.text_system.select_font(&font_struct) {
+            id
         } else {
-            context.text_system.select_font(&font_struct)
+            return Err(Error::new(DWRITE_E_NOFONT, "Failed to select font"));
         };
 
         let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };