Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Cache resolved fonts (#65852)
Kirill Bulatov3389d8757731
diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rsindex cf6bb102936..aedf42e243f 100644--- a/crates/gpui/src/text_system.rs+++ b/crates/gpui/src/text_system.rs@@ -16,7 +16,7 @@ use crate::{Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,};-use anyhow::{Context as _, anyhow};+use anyhow::Context as _;use collections::{FxHashMap, FxHashSet};use core::fmt;use derive_more::{Add, Deref, FromStr, Sub};@@ -229,7 +229,7 @@ impl Drop for MissingGlyphReceiver {/// The GPUI text rendering sub system.pub struct TextSystem {platform_text_system: Arc<dyn PlatformTextSystem>,- font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,+ font_ids_by_font: RwLock<FxHashMap<Font, CachedFont>>,font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,@@ -240,6 +240,13 @@ pub struct TextSystem {missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,}+#[derive(Clone, Copy)]+enum CachedFont {+ Direct(FontId),+ Fallback(FontId),+ Missing,+}+impl TextSystem {/// Create a new TextSystem with the given platform text system.pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {@@ -325,37 +332,12 @@ impl TextSystem {self.missing_glyph_reporter.report(missing_glyphs);}- /// Get the FontId for the configure font family and style.- fn font_id(&self, font: &Font) -> Result<FontId> {- fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {- match font_id {- Ok(font_id) => Ok(*font_id),- Err(err) => Err(anyhow!("{err}")),- }- }-- let font_id = self- .font_ids_by_font- .read()- .get(font)- .map(clone_font_id_result);- if let Some(font_id) = font_id {- font_id- } else {- let font_id = self.platform_text_system.font_id(font);- self.font_ids_by_font- .write()- .insert(font.clone(), clone_font_id_result(&font_id));- font_id- }- }-/// Get the Font for the Font Id.pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {let lock = self.font_ids_by_font.read();lock.iter().filter_map(|(font, result)| match result {- Ok(font_id) if *font_id == id => Some(font.clone()),+ CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),_ => None,}).next()@@ -368,23 +350,12 @@ impl TextSystem {////// Panics if the font and none of the fallbacks can be resolved.pub fn resolve_font(&self, font: &Font) -> FontId {- if let Ok(font_id) = self.font_id(font) {+ if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =+ self.font_ids_by_font.read().get(font).copied()+ {return font_id;}- for fallback in &self.fallback_font_stack {- if let Ok(font_id) = self.font_id(fallback) {- return font_id;- }- }-- panic!(- "failed to resolve font '{}' or any of the fallbacks: {}",- font.family,- self.fallback_font_stack- .iter()- .map(|fallback| &fallback.family)- .join(", ")- );+ self.resolve_font_uncached(font)}/// Prewarm any system font caches needed to shape text.@@ -595,6 +566,65 @@ impl TextSystem {self.platform_text_system.recommended_rendering_mode(font_id, font_size)}++ fn resolve_font_uncached(&self, font: &Font) -> FontId {+ let mut errors = Vec::new();+ let font_id = {+ let mut font_ids = self.font_ids_by_font.upgradable_read();+ if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =+ font_ids.get(font)+ {+ return *font_id;+ }++ let mut lookup_font = |font: &Font| {+ if let Some(cached) = font_ids.get(font) {+ return match cached {+ CachedFont::Direct(font_id) => Some(*font_id),+ CachedFont::Fallback(_) | CachedFont::Missing => None,+ };+ }++ let result = self.platform_text_system.font_id(font);+ let font_id = result.as_ref().ok().copied();+ font_ids.with_upgraded(|font_ids| {+ font_ids.insert(+ font.clone(),+ font_id.map_or(CachedFont::Missing, CachedFont::Direct),+ );+ });+ if let Err(error) = result {+ errors.push((font.clone(), error));+ }+ font_id+ };++ if let Some(font_id) = lookup_font(font) {+ Some(font_id)+ } else {+ let font_id = self.fallback_font_stack.iter().find_map(lookup_font);+ if let Some(font_id) = font_id {+ font_ids.with_upgraded(|font_ids| {+ font_ids.insert(font.clone(), CachedFont::Fallback(font_id));+ });+ }+ font_id+ }+ };+ for (font, error) in errors {+ log::warn!("failed to load font {font:?}: {error:#}");+ }+ font_id.unwrap_or_else(|| {+ panic!(+ "failed to resolve font '{}' or any of the fallbacks: {}",+ font.family,+ self.fallback_font_stack+ .iter()+ .map(|fallback| &fallback.family)+ .join(", ")+ );+ })+ }}/// The GPUI text layout subsystem.@@ -1446,6 +1476,32 @@ pub fn font_name_with_fallbacks_shared<'a>(}}+#[cfg(test)]+mod font_resolution_tests {+ use super::*;+ use crate::NoopTextSystem;++ #[test]+ fn caches_resolved_font_fallbacks() {+ let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));+ let requested = font("Missing Font").bold().italic();+ {+ let mut font_ids = text_system.font_ids_by_font.write();+ font_ids.insert(requested.clone(), CachedFont::Missing);+ for fallback in &text_system.fallback_font_stack {+ font_ids.insert(fallback.clone(), CachedFont::Missing);+ }+ font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));+ }++ assert_eq!(text_system.resolve_font(&requested), FontId(42));+ assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));++ text_system.fallback_font_stack.clear();+ assert_eq!(text_system.resolve_font(&requested), FontId(42));+ }+}+#[cfg(test)]mod missing_glyph_tests {use super::*;diff --git a/crates/gpui_wgpu/src/cosmic_text_system.rs b/crates/gpui_wgpu/src/cosmic_text_system.rsindex b7c38bb10cc..775067518c6 100644--- a/crates/gpui_wgpu/src/cosmic_text_system.rs+++ b/crates/gpui_wgpu/src/cosmic_text_system.rs@@ -1207,8 +1207,14 @@ fn check_is_known_emoji_font(postscript_name: &str) -> bool {#[cfg(test)]mod tests {use super::*;+#[cfg(feature = "test-support")]use std::{cell::RefCell, rc::Rc};+ use std::{+ sync::mpsc,+ thread,+ time::{Duration, Instant},+ };#[test]fn all_font_names_tracks_available_families() -> Result<()> {@@ -1265,6 +1271,70 @@ mod tests {Ok(text_system)}+ #[test]+ fn cached_font_resolution_does_not_wait_for_cold_lookups() -> Result<()> {+ for family in [".ZedSans", "Missing Font"] {+ let platform_text_system = Arc::new(text_system()?);+ let text_system = gpui::TextSystem::new(platform_text_system.clone());+ let cached = gpui::font(family);+ let expected = platform_text_system.font_id(&gpui::font(".ZedSans"))?;+ assert_eq!(text_system.resolve_font(&cached), expected);+ let (sender, receiver) = mpsc::channel();++ thread::scope(|scope| {+ let backend = platform_text_system.0.read();+ let deadline = Instant::now() + Duration::from_secs(5);+ let cold = scope.spawn(|| text_system.resolve_font(&cached.clone().bold()));+ while !platform_text_system.0.is_locked_exclusive() && Instant::now() < deadline {+ thread::yield_now();+ }+ let cold_waiting = platform_text_system.0.is_locked_exclusive();+ let warm = scope.spawn(|| sender.send(text_system.resolve_font(&cached)));+ let result =+ receiver.recv_timeout(deadline.saturating_duration_since(Instant::now()));+ drop(backend);+ let cold_result = cold.join();+ let warm_result = warm.join();++ assert!(cold_waiting);+ assert_eq!(result.expect("cached lookup blocked"), expected);+ assert_eq!(cold_result.expect("cold lookup panicked"), expected);+ warm_result+ .expect("warm lookup panicked")+ .expect("receiver dropped");+ });+ }+ Ok(())+ }++ #[test]+ fn adding_fonts_retries_cached_font_failures() -> Result<()> {+ let platform_text_system = Arc::new(CosmicTextSystem::new_without_system_fonts("Lilex"));+ let text_system = gpui::TextSystem::new(platform_text_system.clone());+ text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;+ let original_fallback = platform_text_system.font_id(&gpui::font(".ZedSans"))?;+ let requests = [+ gpui::Font::default(),+ gpui::font("Lilex"),+ gpui::font("Missing Font"),+ ];+ for requested in &requests {+ assert_eq!(text_system.resolve_font(requested), original_fallback);+ }+ assert_eq!(+ text_system.get_font_for_id(original_fallback),+ Some(gpui::font(".ZedSans"))+ );++ text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?;+ for (requested, resolved) in requests.iter().zip([".SystemUIFont", "Lilex", ".ZedMono"]) {+ let installed = platform_text_system.font_id(&gpui::font(resolved))?;+ assert_ne!(installed, original_fallback);+ assert_eq!(text_system.resolve_font(requested), installed);+ }+ Ok(())+ }+#[test]fn font_properties_describe_the_selected_face() -> Result<()> {let text_system = text_system()?;