Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Remove synchronization from window text layout (#66147)
Lukas Wirth772a8a91006d
diff --git a/crates/editor/src/movement.rs b/crates/editor/src/movement.rsindex 4b6a3f12b5d..577bb9c3abf 100644--- a/crates/editor/src/movement.rs+++ b/crates/editor/src/movement.rs@@ -12,7 +12,7 @@ use multi_buffer::{MultiBufferOffset, MultiBufferRow, MultiBufferSnapshot};use serde::Deserialize;use workspace::searchable::Direction;-use std::{ops::Range, sync::Arc};+use std::{ops::Range, rc::Rc};/// Defines search strategy for items in `movement` module./// `FindRange::SingeLine` only looks for a match on a single line at a time, whereas@@ -26,7 +26,7 @@ pub enum FindRange {/// TextLayoutDetails encompasses everything we need to move vertically/// taking into account variable width characters.pub struct TextLayoutDetails {- pub(crate) text_system: Arc<WindowTextSystem>,+ pub(crate) text_system: Rc<WindowTextSystem>,pub(crate) editor_style: EditorStyle,pub(crate) rem_size: Pixels,pub scroll_anchor: SharedScrollAnchor,diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rsindex 87e9a89ca7e..2955db0073c 100644--- a/crates/gpui/src/text_system.rs+++ b/crates/gpui/src/text_system.rs@@ -25,10 +25,12 @@ use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};use smallvec::{SmallVec, smallvec};use std::{borrow::Cow,+ cell::RefCell,cmp,collections::VecDeque,fmt::{Debug, Display, Formatter},hash::{Hash, Hasher},+ mem,ops::{Deref, DerefMut, Range},sync::{Arc,@@ -233,7 +235,6 @@ pub struct TextSystem {font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,- font_runs_pool: Mutex<Vec<Vec<FontRun>>>,fallback_font_stack: SmallVec<[Font; 2]>,font_generation: Arc<AtomicUsize>,missing_glyph_reporter: Arc<MissingGlyphReporter>,@@ -258,7 +259,6 @@ impl TextSystem {raster_bounds: RwLock::default(),font_ids_by_font: RwLock::default(),wrapper_pool: Mutex::default(),- font_runs_pool: Mutex::default(),fallback_font_stack: smallvec![// TODO: Remove this when Linux have implemented setting fallbacks.font(".ZedMono"),@@ -634,6 +634,7 @@ impl TextSystem {#[derive(Deref)]pub struct WindowTextSystem {line_layout_cache: LineLayoutCache,+ font_runs_buffer: RefCell<Vec<FontRun>>,#[deref]text_system: Arc<TextSystem>,}@@ -646,6 +647,7 @@ impl WindowTextSystem {text_system.platform_text_system.clone(),text_system.font_generation.clone(),),+ font_runs_buffer: RefCell::default(),text_system,}}@@ -789,7 +791,7 @@ impl WindowTextSystem {line_clamp: Option<usize>,) -> Result<SmallVec<[WrappedLine; 1]>> {let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();- let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();+ let mut font_runs = mem::take(&mut *self.font_runs_buffer.borrow_mut());let mut lines = SmallVec::new();let mut max_wrap_lines = line_clamp;@@ -903,7 +905,7 @@ impl WindowTextSystem {process_line(text, 0, end);}- self.font_runs_pool.lock().push(font_runs);+ *self.font_runs_buffer.borrow_mut() = font_runs;Ok(lines)}@@ -924,7 +926,7 @@ impl WindowTextSystem {force_width: Option<Pixels>,) -> Arc<LineLayout> {let mut last_run = None::<&TextRun>;- let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();+ let mut font_runs = mem::take(&mut *self.font_runs_buffer.borrow_mut());font_runs.clear();for run in runs.iter() {@@ -962,7 +964,7 @@ impl WindowTextSystem {force_width,);- self.font_runs_pool.lock().push(font_runs);+ *self.font_runs_buffer.borrow_mut() = font_runs;layout}@@ -1006,7 +1008,7 @@ impl WindowTextSystem {force_width: Option<Pixels>,) -> Option<Arc<LineLayout>> {let mut last_run = None::<&TextRun>;- let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();+ let mut font_runs = mem::take(&mut *self.font_runs_buffer.borrow_mut());font_runs.clear();for run in runs.iter() {@@ -1045,7 +1047,7 @@ impl WindowTextSystem {force_width,);- self.font_runs_pool.lock().push(font_runs);+ *self.font_runs_buffer.borrow_mut() = font_runs;layout}@@ -1068,7 +1070,7 @@ impl WindowTextSystem {materialize_text: impl FnOnce() -> SharedString,) -> Arc<LineLayout> {let mut last_run = None::<&TextRun>;- let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();+ let mut font_runs = mem::take(&mut *self.font_runs_buffer.borrow_mut());font_runs.clear();for run in runs.iter() {@@ -1108,7 +1110,7 @@ impl WindowTextSystem {materialize_text,);- self.font_runs_pool.lock().push(font_runs);+ *self.font_runs_buffer.borrow_mut() = font_runs;layout}diff --git a/crates/gpui/src/text_system/line_layout.rs b/crates/gpui/src/text_system/line_layout.rsindex f0bf1211114..10336f7a34d 100644--- a/crates/gpui/src/text_system/line_layout.rs+++ b/crates/gpui/src/text_system/line_layout.rs@@ -1,9 +1,9 @@use crate::{FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size, point, px};use collections::FxHashMap;-use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};use smallvec::SmallVec;use std::{borrow::Borrow,+ cell::RefCell,hash::{Hash, Hasher},ops::Range,sync::{@@ -456,8 +456,7 @@ impl WrappedLineLayout {}pub(crate) struct LineLayoutCache {- previous_frame: Mutex<FrameCache>,- current_frame: RwLock<FrameCache>,+ state: RefCell<LineLayoutCacheState>,platform_text_system: Arc<dyn PlatformTextSystem>,/// Advances when [`TextSystem::add_fonts`] successfully changes the font database.font_generation: Arc<AtomicUsize>,@@ -465,6 +464,12 @@ pub(crate) struct LineLayoutCache {cached_font_generation: AtomicUsize,}+#[derive(Default)]+struct LineLayoutCacheState {+ previous_frame: FrameCache,+ current_frame: FrameCache,+}+#[derive(Default)]struct FrameCache {lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,@@ -500,8 +505,7 @@ impl LineLayoutCache {) -> Self {let cached_font_generation = font_generation.load(Ordering::Acquire);Self {- previous_frame: Mutex::default(),- current_frame: RwLock::default(),+ state: RefCell::default(),platform_text_system,font_generation,cached_font_generation: AtomicUsize::new(cached_font_generation),@@ -510,7 +514,8 @@ impl LineLayoutCache {pub fn layout_index(&self) -> LineLayoutIndex {let font_generation = self.clear_if_font_generation_changed();- let frame = self.current_frame.read();+ let state = self.state.borrow();+ let frame = &state.current_frame;LineLayoutIndex {font_generation,lines_index: frame.used_lines.len(),@@ -527,8 +532,11 @@ impl LineLayoutCache {{return;}- let mut current_frame = &mut *self.current_frame.write();- let mut previous_frame = &mut *self.previous_frame.lock();+ let mut state = self.state.borrow_mut();+ let LineLayoutCacheState {+ previous_frame,+ current_frame,+ } = &mut *state;for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {if let Some((key, line)) = previous_frame.lines.remove_entry(key) {@@ -570,7 +578,8 @@ impl LineLayoutCache {if index.font_generation != font_generation {return;}- let mut current_frame = &mut *self.current_frame.write();+ let mut state = self.state.borrow_mut();+ let current_frame = &mut state.current_frame;current_frame.used_lines.truncate(index.lines_index);current_frame.used_wrapped_lines@@ -585,18 +594,20 @@ impl LineLayoutCache {pub fn finish_frame(&self) {let _font_generation = self.clear_if_font_generation_changed();- let mut curr_frame = self.current_frame.write();- let mut prev_frame = self.previous_frame.lock();- std::mem::swap(&mut *prev_frame, &mut *curr_frame);- curr_frame.lines.clear();- curr_frame.wrapped_lines.clear();- curr_frame.used_lines.clear();- curr_frame.used_wrapped_lines.clear();-- curr_frame.lines_by_hash.clear();- curr_frame.wrapped_lines_by_hash.clear();- curr_frame.used_lines_by_hash.clear();- curr_frame.used_wrapped_lines_by_hash.clear();+ let LineLayoutCacheState {+ previous_frame,+ current_frame,+ } = &mut *self.state.borrow_mut();+ std::mem::swap(previous_frame, current_frame);+ current_frame.lines.clear();+ current_frame.wrapped_lines.clear();+ current_frame.used_lines.clear();+ current_frame.used_wrapped_lines.clear();++ current_frame.lines_by_hash.clear();+ current_frame.wrapped_lines_by_hash.clear();+ current_frame.used_lines_by_hash.clear();+ current_frame.used_wrapped_lines_by_hash.clear();}pub fn layout_wrapped_line<Text>(@@ -620,21 +631,23 @@ impl LineLayoutCache {force_width: None,} as &dyn AsCacheKeyRef;- let current_frame = self.current_frame.upgradable_read();- if let Some(layout) = current_frame.wrapped_lines.get(key) {+ let state = self.state.borrow();+ if let Some(layout) = state.current_frame.wrapped_lines.get(key) {return layout.clone();}+ drop(state);- let previous_frame_entry = self.previous_frame.lock().wrapped_lines.remove_entry(key);+ let mut state = self.state.borrow_mut();+ let previous_frame_entry = state.previous_frame.wrapped_lines.remove_entry(key);if let Some((key, layout)) = previous_frame_entry {- let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);- current_frame+ state+ .current_frame.wrapped_lines.insert(key.clone(), layout.clone());- current_frame.used_wrapped_lines.push(key);+ state.current_frame.used_wrapped_lines.push(key);layout} else {- drop(current_frame);+ drop(state);let text = SharedString::from(text);let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs, None);let wrap_boundaries = if let Some(wrap_width) = wrap_width {@@ -655,11 +668,12 @@ impl LineLayoutCache {force_width: None,});- let mut current_frame = self.current_frame.write();- current_frame+ let mut state = self.state.borrow_mut();+ state+ .current_frame.wrapped_lines.insert(key.clone(), layout.clone());- current_frame.used_wrapped_lines.push(key);+ state.current_frame.used_wrapped_lines.push(key);layout}@@ -685,13 +699,18 @@ impl LineLayoutCache {force_width,} as &dyn AsCacheKeyRef;- let current_frame = self.current_frame.upgradable_read();- if let Some(layout) = current_frame.lines.get(key) {+ let state = self.state.borrow();+ if let Some(layout) = state.current_frame.lines.get(key) {return layout.clone();}-- let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);- if let Some((key, layout)) = self.previous_frame.lock().lines.remove_entry(key) {+ drop(state);++ let mut state = self.state.borrow_mut();+ let LineLayoutCacheState {+ previous_frame,+ current_frame,+ } = &mut *state;+ if let Some((key, layout)) = previous_frame.lines.remove_entry(key) {current_frame.lines.insert(key.clone(), layout.clone());current_frame.used_lines.push(key);layout@@ -745,8 +764,8 @@ impl LineLayoutCache {force_width,};- let current_frame = self.current_frame.read();- if let Some((_, layout)) = current_frame.lines_by_hash.iter().find(|(key, _)| {+ let state = self.state.borrow();+ if let Some((_, layout)) = state.current_frame.lines_by_hash.iter().find(|(key, _)| {HashedCacheKeyRef {text_hash: key.text_hash,text_len: key.text_len,@@ -759,8 +778,7 @@ impl LineLayoutCache {return Some(layout.clone());}- let previous_frame = self.previous_frame.lock();- if let Some((_, layout)) = previous_frame.lines_by_hash.iter().find(|(key, _)| {+ if let Some((_, layout)) = state.previous_frame.lines_by_hash.iter().find(|(key, _)| {HashedCacheKeyRef {text_hash: key.text_hash,text_len: key.text_len,@@ -804,8 +822,8 @@ impl LineLayoutCache {};// Fast path: already cached (no allocation).- let current_frame = self.current_frame.upgradable_read();- if let Some((_, layout)) = current_frame.lines_by_hash.iter().find(|(key, _)| {+ let mut state = self.state.borrow_mut();+ if let Some((_, layout)) = state.current_frame.lines_by_hash.iter().find(|(key, _)| {HashedCacheKeyRef {text_hash: key.text_hash,text_len: key.text_len,@@ -818,12 +836,10 @@ impl LineLayoutCache {return layout.clone();}- let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);-// Try to reuse from previous frame without allocating; do a linear scan to find a matching key.// (We avoid `drain()` here because it would eagerly move all entries.)- let mut previous_frame = self.previous_frame.lock();- if let Some(existing_key) = previous_frame+ if let Some(existing_key) = state+ .previous_frame.used_lines_by_hash.iter().find(|key| {@@ -838,14 +854,20 @@ impl LineLayoutCache {}).cloned(){- if let Some((key, layout)) = previous_frame.lines_by_hash.remove_entry(&existing_key) {- current_frame+ if let Some((key, layout)) = state+ .previous_frame+ .lines_by_hash+ .remove_entry(&existing_key)+ {+ state+ .current_frame.lines_by_hash.insert(key.clone(), layout.clone());- current_frame.used_lines_by_hash.push(key);+ state.current_frame.used_lines_by_hash.push(key);return layout;}}+ drop(state);let text = materialize_text();let mut layout = self@@ -865,10 +887,12 @@ impl LineLayoutCache {force_width,});let layout = Arc::new(layout);- current_frame+ let mut state = self.state.borrow_mut();+ state+ .current_frame.lines_by_hash.insert(key.clone(), layout.clone());- current_frame.used_lines_by_hash.push(key);+ state.current_frame.used_lines_by_hash.push(key);layout}@@ -878,13 +902,12 @@ impl LineLayoutCache {return font_generation;}- let mut current_frame = self.current_frame.write();+ let mut state = self.state.borrow_mut();if self.cached_font_generation.load(Ordering::Acquire) == font_generation {return font_generation;}- *current_frame = FrameCache::default();- *self.previous_frame.lock() = FrameCache::default();+ *state = LineLayoutCacheState::default();self.cached_font_generation.store(font_generation, Ordering::Release);font_generationdiff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex c559412e560..ad0e7e067cf 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -1231,7 +1231,7 @@ pub struct Window {is_resizable: bool,is_minimizable: bool,sprite_atlas: Arc<dyn PlatformAtlas>,- text_system: Arc<WindowTextSystem>,+ text_system: Rc<WindowTextSystem>,text_rendering_mode: Rc<Cell<TextRenderingMode>>,rem_size: Pixels,/// The stack of override values for the window's rem size.@@ -1653,7 +1653,7 @@ impl Window {let content_size = platform_window.content_size();let scale_factor = platform_window.scale_factor();let appearance = platform_window.appearance();- let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));+ let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));let invalidator = WindowInvalidator::new(handle.window_id());let active = Rc::new(Cell::new(platform_window.is_active()));let visibility = platform_window.visibility();@@ -2471,7 +2471,7 @@ impl Window {}/// Accessor for the text system.- pub fn text_system(&self) -> &Arc<WindowTextSystem> {+ pub fn text_system(&self) -> &Rc<WindowTextSystem> {&self.text_system}