Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Some gpui cleanups (#66156)
Lukas Wirthdde76a1dca53
diff --git a/Cargo.lock b/Cargo.lockindex a23f1751962..70ffd0928a8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7354,7 +7354,6 @@ dependencies = ["chrono","collections","criterion",- "ctor","derive_more","dioxus-cli-config","dioxus-devtools-types",diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.tomlindex a46c580fc1d..bb25fbea9b7 100644--- a/crates/gpui/Cargo.toml+++ b/crates/gpui/Cargo.toml@@ -68,7 +68,6 @@ bitflags.workspace = truecollections.workspace = truebench_metrics = { workspace = true, optional = true }criterion = { workspace = true, optional = true }-ctor.workspace = truederive_more = { workspace = true, features = ["add", "add_assign", "mul", "mul_assign", "not"] }etagere.workspace = truefutures.workspace = truediff --git a/crates/gpui/src/action.rs b/crates/gpui/src/action.rsindex 07c47fc2e4a..e50782ff49b 100644--- a/crates/gpui/src/action.rs+++ b/crates/gpui/src/action.rs@@ -194,13 +194,13 @@ pub enum ActionBuildError {/// Indicates that an action with this name has not been registered.NotFound {/// Name of the action that was not found.- name: String,+ name: Box<str>,},/// Indicates that an error occurred while building the action, typically a JSON deserialization/// error.BuildError {/// Name of the action that was attempting to be built.- name: String,+ name: Box<str>,/// Error that occurred while building the action.error: anyhow::Error,},@@ -356,13 +356,11 @@ impl ActionRegistry {let build_action = self.by_name.get(name)- .ok_or_else(|| ActionBuildError::NotFound {- name: name.to_owned(),- })?+ .ok_or_else(|| ActionBuildError::NotFound { name: name.into() })?.build;(build_action)(params.unwrap_or_else(|| json!({}))).map_err(|e| {ActionBuildError::BuildError {- name: name.to_owned(),+ name: name.into(),error: e,}})diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rsindex 0f1d59b4f6b..8167c2e6b9b 100644--- a/crates/gpui/src/app.rs+++ b/crates/gpui/src/app.rs@@ -43,6 +43,7 @@ pub use visual_test_context::*;#[cfg(any(feature = "inspector", debug_assertions))]use crate::InspectorElementRegistry;use crate::asset_cache::CachedLoad;+use crate::subscription::SingleSubscriberSet;use crate::{Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetSource,@@ -322,7 +323,7 @@ impl Application {/// Register a handler to be invoked when the platform instructs the application/// to open one or more URLs.- pub fn on_open_urls<F>(&self, mut callback: F) -> &Self+ pub fn on_open_urls<F>(&self, callback: F) -> &SelfwhereF: 'static + FnMut(Vec<String>),{@@ -574,7 +575,7 @@ impl SystemWindowTabController {let current_group = current_group?;// TODO: `.keys()` returns arbitrary order, what does "next" mean?- let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();+ let group_ids: Vec<_> = controller.tab_groups.keys().collect();let idx = group_ids.iter().position(|g| *g == current_group)?;let next_idx = (idx + 1) % group_ids.len();@@ -599,7 +600,7 @@ impl SystemWindowTabController {let current_group = current_group?;// TODO: `.keys()` returns arbitrary order, what does "previous" mean?- let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();+ let group_ids: Vec<_> = controller.tab_groups.keys().collect();let idx = group_ids.iter().position(|g| *g == current_group)?;let prev_idx = if idx == 0 {group_ids.len() - 1@@ -627,7 +628,7 @@ impl SystemWindowTabController {/// Initialize the visibility of the system window tab controller.pub fn init_visible(cx: &mut App, visible: bool) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();if controller.visible.is_none() {controller.visible = Some(visible);}@@ -640,13 +641,13 @@ impl SystemWindowTabController {/// Set the visibility of the system window tab controller.pub fn set_visible(cx: &mut App, visible: bool) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();controller.visible = Some(visible);}/// Update the last active of a window.pub fn update_last_active(cx: &mut App, id: WindowId) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();for windows in controller.tab_groups.values_mut() {for tab in windows.iter_mut() {if tab.id == id {@@ -658,7 +659,7 @@ impl SystemWindowTabController {/// Update the position of a tab within its group.pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();for (_, windows) in controller.tab_groups.iter_mut() {if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {if ix < windows.len() && current_pos != ix {@@ -683,7 +684,7 @@ impl SystemWindowTabController {return;}- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();for windows in controller.tab_groups.values_mut() {for tab in windows.iter_mut() {if tab.id == id {@@ -696,12 +697,12 @@ impl SystemWindowTabController {/// Insert a tab into a tab group.pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {return;};- let mut expected_tab_ids: Vec<_> = tabs+ let expected_tab_ids: Vec<_> = tabs.iter().filter(|tab| tab.id != id).map(|tab| tab.id)@@ -729,7 +730,7 @@ impl SystemWindowTabController {/// Remove a tab from a tab group.pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();let mut removed_tab = None;controller.tab_groups.retain(|_, tabs| {@@ -744,8 +745,8 @@ impl SystemWindowTabController {/// Move a tab to a new tab group.pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {- let mut removed_tab = Self::remove_tab(cx, id);- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let removed_tab = Self::remove_tab(cx, id);+ let controller = cx.global_mut::<SystemWindowTabController>();if let Some(tab) = removed_tab {let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);@@ -755,7 +756,7 @@ impl SystemWindowTabController {/// Merge all tab groups into a single group.pub fn merge_all_windows(cx: &mut App, id: WindowId) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();let Some(initial_tabs) = controller.tabs(id) else {return;};@@ -773,7 +774,7 @@ impl SystemWindowTabController {/// Selects the next tab in the tab group in the trailing direction.pub fn select_next_tab(cx: &mut App, id: WindowId) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();let Some(tabs) = controller.tabs(id) else {return;};@@ -788,7 +789,7 @@ impl SystemWindowTabController {/// Selects the previous tab in the tab group in the leading direction.pub fn select_previous_tab(cx: &mut App, id: WindowId) {- let mut controller = cx.global_mut::<SystemWindowTabController>();+ let controller = cx.global_mut::<SystemWindowTabController>();let Some(tabs) = controller.tabs(id) else {return;};@@ -875,24 +876,24 @@ pub struct App {pub(crate) observers: SubscriberSet<EntityId, Handler>,pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,- pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,- pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,- pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,+ pub(crate) keystroke_observers: SingleSubscriberSet<KeystrokeObserver>,+ pub(crate) keystroke_interceptors: SingleSubscriberSet<KeystrokeObserver>,+ pub(crate) keyboard_layout_observers: SingleSubscriberSet<Handler>,missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,- pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,- pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,+ pub(crate) thermal_state_observers: SingleSubscriberSet<Handler>,+ pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,/// The connected displays, as of the platform's last display change/// notification.displays: HashMap<DisplayId, DisplayState>,- pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,- pub(crate) system_wake_observers: SubscriberSet<(), Handler>,- app_lifecycle_observers: SubscriberSet<(), AppLifecycleHandler>,- memory_warning_observers: SubscriberSet<(), Handler>,+ pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,+ pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,+ app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,+ memory_warning_observers: SingleSubscriberSet<Handler>,pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,pub(crate) global_observers: SubscriberSet<TypeId, Handler>,- pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,- pub(crate) restart_observers: SubscriberSet<(), Handler>,- pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,+ pub(crate) quit_observers: SingleSubscriberSet<QuitHandler>,+ pub(crate) restart_observers: SingleSubscriberSet<Handler>,+ pub(crate) window_closed_observers: SingleSubscriberSet<WindowClosedHandler>,/// Per-App element arena. This isolates element allocations between different/// App instances (important for tests where multiple Apps run concurrently).@@ -1018,23 +1019,23 @@ impl App {current_window_by_entity: FxHashMap::default(),event_listeners: SubscriberSet::new(),release_listeners: SubscriberSet::new(),- keystroke_observers: SubscriberSet::new(),- keystroke_interceptors: SubscriberSet::new(),- keyboard_layout_observers: SubscriberSet::new(),+ keystroke_observers: SingleSubscriberSet::new(),+ keystroke_interceptors: SingleSubscriberSet::new(),+ keyboard_layout_observers: SingleSubscriberSet::new(),missing_glyph_callback: Rc::default(),- thermal_state_observers: SubscriberSet::new(),- display_observers: SubscriberSet::new(),+ thermal_state_observers: SingleSubscriberSet::new(),+ display_observers: SingleSubscriberSet::new(),displays: read_displays(platform.as_ref()),- system_sleep_observers: SubscriberSet::new(),- system_wake_observers: SubscriberSet::new(),- app_lifecycle_observers: SubscriberSet::new(),- memory_warning_observers: SubscriberSet::new(),+ system_sleep_observers: SingleSubscriberSet::new(),+ system_wake_observers: SingleSubscriberSet::new(),+ app_lifecycle_observers: SingleSubscriberSet::new(),+ memory_warning_observers: SingleSubscriberSet::new(),global_observers: SubscriberSet::new(),- quit_observers: SubscriberSet::new(),- restart_observers: SubscriberSet::new(),+ quit_observers: SingleSubscriberSet::new(),+ restart_observers: SingleSubscriberSet::new(),restart_path: None,restart_arguments: Vec::new(),- window_closed_observers: SubscriberSet::new(),+ window_closed_observers: SingleSubscriberSet::new(),layout_id_buffer: Default::default(),propagate_event: true,prompt_builder: Some(PromptBuilder::Default),@@ -1073,7 +1074,7 @@ impl App {cx.keyboard_mapper = cx.platform.keyboard_mapper();cx.keyboard_layout_observers.clone()- .retain(&(), move |callback| (callback)(cx));+ .retain(move |callback| (callback)(cx));}}}));@@ -1085,7 +1086,7 @@ impl App {let cx = &mut app.borrow_mut();cx.thermal_state_observers.clone()- .retain(&(), move |callback| (callback)(cx));+ .retain(move |callback| (callback)(cx));}}}));@@ -1106,7 +1107,7 @@ impl App {let cx = &mut app.borrow_mut();cx.system_sleep_observers.clone()- .retain(&(), move |callback| (callback)(cx));+ .retain(move |callback| (callback)(cx));}}}));@@ -1118,7 +1119,7 @@ impl App {let cx = &mut app.borrow_mut();cx.system_wake_observers.clone()- .retain(&(), move |callback| (callback)(cx));+ .retain(move |callback| (callback)(cx));}}}));@@ -1130,7 +1131,7 @@ impl App {app.borrow_mut().update(|cx| {cx.app_lifecycle_observers.clone()- .retain(&(), |callback| callback(phase, cx));+ .retain(|callback| callback(phase, cx));});}}@@ -1143,7 +1144,7 @@ impl App {app.borrow_mut().update(|cx| {cx.memory_warning_observers.clone()- .retain(&(), |callback| callback(cx));+ .retain(|callback| callback(cx));});}}@@ -1230,7 +1231,7 @@ impl App {let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();- for observer in self.quit_observers.remove(&()) {+ for observer in self.quit_observers.remove() {futures.push(observer(self));}@@ -1281,15 +1282,10 @@ impl App {whereF: 'static + FnMut(&mut App),{- let (subscription, activate) = self.keyboard_layout_observers.insert(- (),- Box::new(move |cx| {- callback(cx);- true- }),- );- activate();- subscription+ self.keyboard_layout_observers.insert(Box::new(move |cx| {+ callback(cx);+ true+ }))}/// Gracefully quit the application via the platform's standard routine.@@ -1455,7 +1451,7 @@ impl App {}pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {- let (subscription, activate) = self.observers.insert(key, value);+ let (subscription, activate) = self.observers.insert_pending(key, value);self.defer(move |_| activate());subscription}@@ -1504,7 +1500,7 @@ impl App {key: EntityId,value: (TypeId, Listener),) -> Subscription {- let (subscription, activate) = self.event_listeners.insert(key, value);+ let (subscription, activate) = self.event_listeners.insert_pending(key, value);self.defer(move |_| activate());subscription}@@ -1662,15 +1658,10 @@ impl App {whereF: 'static + FnMut(&mut App),{- let (subscription, activate) = self.thermal_state_observers.insert(- (),- Box::new(move |cx| {- callback(cx);- true- }),- );- activate();- subscription+ self.thermal_state_observers.insert(Box::new(move |cx| {+ callback(cx);+ true+ }))}/// Invokes a handler when the system is about to sleep.@@ -1681,15 +1672,10 @@ impl App {whereF: 'static + FnMut(&mut App),{- let (subscription, activate) = self.system_sleep_observers.insert(- (),- Box::new(move |cx| {- callback(cx);- true- }),- );- activate();- subscription+ self.system_sleep_observers.insert(Box::new(move |cx| {+ callback(cx);+ true+ }))}pub(crate) fn displays_changed(&mut self) {@@ -1712,7 +1698,7 @@ impl App {for event in events {self.display_observers.clone()- .retain(&(), |callback| (callback)(event, self));+ .retain(|callback| (callback)(event, self));}}@@ -1732,15 +1718,10 @@ impl App {whereF: 'static + FnMut(DisplayEvent, &mut App),{- let (subscription, activate) = self.display_observers.insert(- (),- Box::new(move |event, cx| {- callback(event, cx);- true- }),- );- activate();- subscription+ self.display_observers.insert(Box::new(move |event, cx| {+ callback(event, cx);+ true+ }))}/// Invokes a handler when the system wakes from sleep.@@ -1748,15 +1729,10 @@ impl App {whereF: 'static + FnMut(&mut App),{- let (subscription, activate) = self.system_wake_observers.insert(- (),- Box::new(move |cx| {- callback(cx);- true- }),- );- activate();- subscription+ self.system_wake_observers.insert(Box::new(move |cx| {+ callback(cx);+ true+ }))}/// Observes mobile application lifecycle changes. Desktop platforms do not@@ -1770,29 +1746,20 @@ impl App {&self,mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,) -> Subscription {- let (subscription, activate) = self.app_lifecycle_observers.insert(- (),- Box::new(move |phase, cx| {+ self.app_lifecycle_observers+ .insert(Box::new(move |phase, cx| {callback(phase, cx);true- }),- );- activate();- subscription+ }))}/// Observes mobile memory-pressure warnings so applications can release/// expendable caches. Dropping the subscription removes the observer.pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {- let (subscription, activate) = self.memory_warning_observers.insert(- (),- Box::new(move |cx| {- callback(cx);- true- }),- );- activate();- subscription+ self.memory_warning_observers.insert(Box::new(move |cx| {+ callback(cx);+ true+ }))}/// Returns the appearance of the application's windows.@@ -2052,7 +2019,7 @@ impl App {pub fn restart(&mut self) {self.restart_observers.clone()- .retain(&(), |observer| observer(self));+ .retain(|observer| observer(self));self.platform.restart(self.restart_path.take(),std::mem::take(&mut self.restart_arguments),@@ -2586,7 +2553,7 @@ impl App {&mut self,mut f: impl FnMut(&mut Self) + 'static,) -> Subscription {- let (subscription, activate) = self.global_observers.insert(+ let (subscription, activate) = self.global_observers.insert_pending(TypeId::of::<G>(),Box::new(move |cx| {f(cx);@@ -2621,9 +2588,7 @@ impl App {key: TypeId,value: NewEntityListener,) -> Subscription {- let (subscription, activate) = self.new_entity_observers.insert(key, value);- activate();- subscription+ self.new_entity_observers.insert(key, value)}/// Arrange for the given function to be invoked whenever a view of the specified type is created.@@ -2657,15 +2622,13 @@ impl App {whereT: 'static,{- let (subscription, activate) = self.release_listeners.insert(+ self.release_listeners.insert(handle.entity_id(),Box::new(move |entity, cx| {let entity = entity.downcast_mut().expect("invalid entity type");on_release(entity, cx)}),- );- activate();- subscription+ )}/// Observe the release of a entity. The callback is invoked after the entity@@ -2693,22 +2656,11 @@ impl App {&mut self,mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,) -> Subscription {- fn inner(- keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,- handler: KeystrokeObserver,- ) -> Subscription {- let (subscription, activate) = keystroke_observers.insert((), handler);- activate();- subscription- }-- inner(- &self.keystroke_observers,- Box::new(move |event, window, cx| {+ self.keystroke_observers+ .insert(Box::new(move |event, window, cx| {f(event, window, cx);true- }),- )+ }))}/// Register a callback to be invoked when a keystroke is received by the application@@ -2719,22 +2671,11 @@ impl App {&mut self,mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,) -> Subscription {- fn inner(- keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,- handler: KeystrokeObserver,- ) -> Subscription {- let (subscription, activate) = keystroke_interceptors.insert((), handler);- activate();- subscription- }-- inner(- &self.keystroke_interceptors,- Box::new(move |event, window, cx| {+ self.keystroke_interceptors+ .insert(Box::new(move |event, window, cx| {f(event, window, cx);true- }),- )+ }))}/// Register key bindings.@@ -2855,41 +2796,29 @@ impl App {whereFut: 'static + Future<Output = ()>,{- let (subscription, activate) = self.quit_observers.insert(- (),- Box::new(move |cx| {- let future = on_quit(cx);- future.boxed_local()- }),- );- activate();- subscription+ self.quit_observers.insert(Box::new(move |cx| {+ let future = on_quit(cx);+ future.boxed_local()+ }))}/// Register a callback to be invoked when the application is about to restart.////// These callbacks are called before any `on_app_quit` callbacks.pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {- let (subscription, activate) = self.restart_observers.insert(- (),- Box::new(move |cx| {- on_restart(cx);- true- }),- );- activate();- subscription+ self.restart_observers.insert(Box::new(move |cx| {+ on_restart(cx);+ true+ }))}/// Register a callback to be invoked when a window is closed/// The window is no longer accessible at the point this callback is invoked.pub fn on_window_closed(&self,- mut on_closed: impl FnMut(&mut App, WindowId) + 'static,+ on_closed: impl FnMut(&mut App, WindowId) + 'static,) -> Subscription {- let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));- activate();- subscription+ self.window_closed_observers.insert(Box::new(on_closed))}pub(crate) fn clear_pending_keystrokes(&mut self) {@@ -3307,7 +3236,7 @@ impl App {}}- cx.window_closed_observers.clone().retain(&(), |callback| {+ cx.window_closed_observers.clone().retain(|callback| {callback(cx, window_id);true});@@ -3478,7 +3407,7 @@ impl AppContext for App {whereG: Global,{- let mut g = self.global::<G>();+ let g = self.global::<G>();callback(g, self)}}diff --git a/crates/gpui/src/app/context.rs b/crates/gpui/src/app/context.rsindex 7840c9f7440..aba73617e38 100644--- a/crates/gpui/src/app/context.rs+++ b/crates/gpui/src/app/context.rs@@ -1,8 +1,7 @@use crate::{AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,- FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,- SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,- WindowVisibility,+ FocusHandle, FocusOutEvent, Focusable, Global, Priority, Reservation, Subscription, Task,+ WeakEntity, WeakFocusHandle, Window, WindowHandle, WindowVisibility,};use anyhow::Result;use futures::FutureExt;@@ -128,15 +127,13 @@ impl<'a, T: 'static> Context<'a, T> {whereT: 'static,{- let (subscription, activate) = self.app.release_listeners.insert(+ self.app.release_listeners.insert(self.entity_state.entity_id,Box::new(move |this, cx| {let this = this.downcast_mut().expect("invalid entity type");on_release(this, cx);}),- );- activate();- subscription+ )}/// Register a callback to be run on the release of another entity@@ -151,7 +148,7 @@ impl<'a, T: 'static> Context<'a, T> {{let entity_id = entity.entity_id();let this = self.weak_entity();- let (subscription, activate) = self.app.release_listeners.insert(+ self.app.release_listeners.insert(entity_id,Box::new(move |entity, cx| {let entity = entity.downcast_mut().expect("invalid entity type");@@ -159,9 +156,7 @@ impl<'a, T: 'static> Context<'a, T> {this.update(cx, |this, cx| on_release(this, entity, cx));}}),- );- activate();- subscription+ )}/// Register a callback to for updates to the given global@@ -173,7 +168,7 @@ impl<'a, T: 'static> Context<'a, T> {T: 'static,{let handle = self.weak_entity();- let (subscription, activate) = self.global_observers.insert(+ let (subscription, activate) = self.global_observers.insert_pending(TypeId::of::<G>(),Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),);@@ -405,15 +400,10 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.bounds_observers.insert(- (),- Box::new(move |window, cx| {- view.update(cx, |view, cx| callback(view, window, cx))- .is_ok()- }),- );- activate();- subscription+ window.bounds_observers.insert(Box::new(move |window, cx| {+ view.update(cx, |view, cx| callback(view, window, cx))+ .is_ok()+ }))}/// Register a callback to be invoked when the window is activated or deactivated.@@ -423,15 +413,12 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.activation_observers.insert(- (),- Box::new(move |window, cx| {+ window+ .activation_observers+ .insert(Box::new(move |window, cx| {view.update(cx, |view, cx| callback(view, window, cx)).is_ok()- }),- );- activate();- subscription+ }))}/// Registers a callback to be invoked when the window's visibility changes@@ -442,15 +429,12 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.visibility_observers.insert(- (),- Box::new(move |visibility, window, cx| {+ window+ .visibility_observers+ .insert(Box::new(move |visibility, window, cx| {view.update(cx, |view, cx| callback(view, visibility, window, cx)).is_ok()- }),- );- activate();- subscription+ }))}/// Registers a callback to be invoked when the window appearance changes.@@ -460,15 +444,12 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.appearance_observers.insert(- (),- Box::new(move |window, cx| {+ window+ .appearance_observers+ .insert(Box::new(move |window, cx| {view.update(cx, |view, cx| callback(view, window, cx)).is_ok()- }),- );- activate();- subscription+ }))}/// Registers a callback invoked when the window moves to another display@@ -480,15 +461,10 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.display_observers.insert(- (),- Box::new(move |window, cx| {- view.update(cx, |view, cx| callback(view, window, cx))- .is_ok()- }),- );- activate();- subscription+ window.display_observers.insert(Box::new(move |window, cx| {+ view.update(cx, |view, cx| callback(view, window, cx))+ .is_ok()+ }))}/// Registers a callback to be invoked when the window button layout changes.@@ -498,15 +474,12 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.button_layout_observers.insert(- (),- Box::new(move |window, cx| {+ window+ .button_layout_observers+ .insert(Box::new(move |window, cx| {view.update(cx, |view, cx| callback(view, window, cx)).is_ok()- }),- );- activate();- subscription+ }))}/// Registers a callback for [`App::observe_keystrokes`] that updates this entity.@@ -514,27 +487,16 @@ impl<'a, T: 'static> Context<'a, T> {&mut self,mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,) -> Subscription {- fn inner(- keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,- handler: KeystrokeObserver,- ) -> Subscription {- let (subscription, activate) = keystroke_observers.insert((), handler);- activate();- subscription- }-let view = self.weak_entity();- inner(- &self.keystroke_observers,- Box::new(move |event, window, cx| {+ self.keystroke_observers+ .insert(Box::new(move |event, window, cx| {if let Some(view) = view.upgrade() {view.update(cx, |view, cx| f(view, event, window, cx));true} else {false}- }),- )+ }))}/// Register a callback to be invoked when the window's pending input changes.@@ -544,15 +506,12 @@ impl<'a, T: 'static> Context<'a, T> {mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.pending_input_observers.insert(- (),- Box::new(move |window, cx| {+ window+ .pending_input_observers+ .insert(Box::new(move |window, cx| {view.update(cx, |view, cx| callback(view, window, cx)).is_ok()- }),- );- activate();- subscription+ }))}/// Register a listener to be called when the given focus handle receives focus.@@ -639,13 +598,13 @@ impl<'a, T: 'static> Context<'a, T> {mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,) -> Subscription {let view = self.weak_entity();- let (subscription, activate) = window.focus_lost_listeners.insert(- (),- Box::new(move |window, cx| {- view.update(cx, |view, cx| listener(view, window, cx))- .is_ok()- }),- );+ let (subscription, activate) =+ window+ .focus_lost_listeners+ .insert_pending(Box::new(move |window, cx| {+ view.update(cx, |view, cx| listener(view, window, cx))+ .is_ok()+ }));self.defer(|_| activate());subscription}@@ -724,7 +683,7 @@ impl<'a, T: 'static> Context<'a, T> {) -> Subscription {let window_handle = window.handle;let view = self.weak_entity();- let (subscription, activate) = self.global_observers.insert(+ let (subscription, activate) = self.global_observers.insert_pending(TypeId::of::<G>(),Box::new(move |cx| {// If the entity has been dropped, remove this observer.diff --git a/crates/gpui/src/app/entity_map.rs b/crates/gpui/src/app/entity_map.rsindex 38ba7604f77..129b30438e0 100644--- a/crates/gpui/src/app/entity_map.rs+++ b/crates/gpui/src/app/entity_map.rs@@ -125,7 +125,7 @@ impl EntityMap {whereT: 'static,{- let mut accessed_entities = self.accessed_entities.get_mut();+ let accessed_entities = self.accessed_entities.get_mut();accessed_entities.insert(slot.entity_id);let handle = slot.0;@@ -188,9 +188,9 @@ impl EntityMap {}pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {- let mut ref_counts = &mut *self.ref_counts.write();+ let ref_counts = &mut *self.ref_counts.write();let dropped_entity_ids = ref_counts.dropped_entity_ids.drain(..);- let mut accessed_entities = self.accessed_entities.get_mut();+ let accessed_entities = self.accessed_entities.get_mut();dropped_entity_ids.filter_map(|entity_id| {diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rsindex 54b72a63ec5..d1797d5ff18 100644--- a/crates/gpui/src/app/test_context.rs+++ b/crates/gpui/src/app/test_context.rs@@ -757,7 +757,7 @@ impl<T: 'static> Entity<T> {Event: Send + Clone + 'static,T: EventEmitter<Event>,{- let (tx, mut rx) = oneshot::channel();+ let (tx, rx) = oneshot::channel();let mut tx = Some(tx);let subscription = self.update(cx, |_, cx| {cx.subscribe(self, move |_, _, event, _| {diff --git a/crates/gpui/src/app/visual_test_context.rs b/crates/gpui/src/app/visual_test_context.rsindex 17e3a454505..23fedc4ec5b 100644--- a/crates/gpui/src/app/visual_test_context.rs+++ b/crates/gpui/src/app/visual_test_context.rs@@ -73,7 +73,7 @@ impl VisualTestAppContext {let http_client = http_client::FakeHttpClient::with_404_response();- let mut app = App::new_app(platform.clone(), asset_source, http_client);+ let app = App::new_app(platform.clone(), asset_source, http_client);app.borrow_mut().mode = GpuiMode::test();Self {diff --git a/crates/gpui/src/bench.rs b/crates/gpui/src/bench.rsnew file mode 100644index 00000000000..b1e27b15108--- /dev/null+++ b/crates/gpui/src/bench.rs@@ -0,0 +1,65 @@+/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].+///+/// This mirrors `criterion::criterion_group!`, but the group measures with the+/// `gpui::BenchMeasurement` configured by `BENCH_MEASUREMENT` (see+/// `BenchMeasurement::from_env`). By default Criterion analyzes wall time+/// while retired instructions, cycles, IPC, context switches, and the other+/// counters this machine supports are printed per iteration in the GPUI bench+/// report. `BENCH_MEASUREMENT=instructions` makes Criterion analyze+/// process-wide instructions instead, `foreground-instructions` the benchmark+/// thread's alone, and `wall-time` disables all counters. A+/// `config = ...` expression may set any other Criterion option; its+/// measurement is replaced. To measure with something else, call+/// `criterion::criterion_group!` directly with+/// `config = criterion::Criterion::default().with_measurement(gpui::BenchMeasurement::new(...))`.+///+/// [`gpui::bench`]: crate::bench+#[macro_export]+macro_rules! bench_group {+ (name = $name:ident; config = $config:expr; targets = $($target:path),+ $(,)?) => {+ criterion::criterion_group! {+ name = $name;+ config = ($config).with_measurement($crate::BenchMeasurement::from_env_or_exit());+ targets = $($target),++ }+ };+ ($name:ident, $($target:path),+ $(,)?) => {+ $crate::bench_group! {+ name = $name;+ config = criterion::Criterion::default();+ targets = $($target),++ }+ };+}++/// Defines the entry point for GPUI Criterion benchmark groups.+///+/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the+/// same shape as ordinary Criterion benchmarks. It also installs+/// [`CountingAllocator`] as the binary's global allocator, so reports include+/// heap allocations per iteration. It wraps the system allocator by default;+/// `allocator = Path;` wraps another unit-struct allocator instead, e.g. to+/// compare allocators, which pay the same small counting cost:+///+/// ```ignore+/// gpui::bench_main!(allocator = mimalloc::MiMalloc; benches);+/// ```+///+/// `allocator = none;` installs no global allocator, leaving Rust's default and+/// dropping the allocation metrics from reports.+#[macro_export]+macro_rules! bench_main {+ (allocator = none; $($groups:tt)*) => {+ criterion::criterion_main!($($groups)*);+ };+ (allocator = $allocator:path; $($groups:tt)*) => {+ #[global_allocator]+ static GPUI_BENCH_ALLOCATOR: $crate::CountingAllocator<$allocator> =+ $crate::CountingAllocator::new($allocator);++ criterion::criterion_main!($($groups)*);+ };+ ($($groups:tt)*) => {+ $crate::bench_main!(allocator = ::std::alloc::System; $($groups)*);+ };+}diff --git a/crates/gpui/src/colors.rs b/crates/gpui/src/colors.rsindex ef11ef57fdb..18e7983f424 100644--- a/crates/gpui/src/colors.rs+++ b/crates/gpui/src/colors.rs@@ -1,3 +1,4 @@+//! The default colors used by GPUI.use crate::{App, Global, Rgba, Window, WindowAppearance, rgb};use std::ops::Deref;use std::sync::Arc;diff --git a/crates/gpui/src/element.rs b/crates/gpui/src/element.rsindex cedf3046c77..8f980bd53a9 100644--- a/crates/gpui/src/element.rs+++ b/crates/gpui/src/element.rs@@ -946,7 +946,7 @@ mod global_element_id_tests {for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });let window = crate::AnyWindowHandle::from(window);- let mut frame = |cx: &mut crate::TestAppContext| {+ let frame = |cx: &mut crate::TestAppContext| {cx.update_window(window, |_, window, cx| {window.refresh();let started = std::time::Instant::now();diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rsindex 11f0b72406a..109acd49d0a 100644--- a/crates/gpui/src/elements/div.rs+++ b/crates/gpui/src/elements/div.rs@@ -2501,7 +2501,7 @@ impl Interactivity {.tracked_scroll_handle.as_ref().map(|handle| handle.0.borrow_mut());- if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {+ if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {scroll_handle_state.overflow = style.overflow;scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);}@@ -4456,7 +4456,7 @@ impl ScrollHandle {/// Set the offset explicitly. The offset is the distance from the top left of the/// parent container to the top left of the first child./// As you scroll further down the offset becomes more negative.- pub fn set_offset(&self, mut position: Point<Pixels>) {+ pub fn set_offset(&self, position: Point<Pixels>) {let state = self.0.borrow();*state.offset.borrow_mut() = position;}@@ -5141,7 +5141,7 @@ mod tests {fn tooltip_respects_custom_show_delay() {let extra_delay = Duration::from_secs(1);let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;- let (mut test_app, _any_window, captured_active_tooltip) =+ let (test_app, _any_window, captured_active_tooltip) =setup_tooltip_owner_test(Some(show_delay_override));let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();diff --git a/crates/gpui/src/elements/image_cache.rs b/crates/gpui/src/elements/image_cache.rsindex 84948145aa8..1920944299b 100644--- a/crates/gpui/src/elements/image_cache.rs+++ b/crates/gpui/src/elements/image_cache.rs@@ -320,7 +320,7 @@ impl ImageCacheProvider for RetainAllImageCacheProvider {window.with_element_state::<Entity<RetainAllImageCache>, _>(global_id,|cache, _window| {- let mut cache = cache.unwrap_or_else(|| RetainAllImageCache::new(cx));+ let cache = cache.unwrap_or_else(|| RetainAllImageCache::new(cx));(cache.clone(), cache)},)diff --git a/crates/gpui/src/elements/list.rs b/crates/gpui/src/elements/list.rsindex f42c25bc1da..4adaac16cd9 100644--- a/crates/gpui/src/elements/list.rs+++ b/crates/gpui/src/elements/list.rs@@ -1011,7 +1011,7 @@ impl StateInner {}}- let mut cursor = self.items.cursor::<Count>(());+ let cursor = self.items.cursor::<Count>(());let available_item_space = size(AvailableSpace::Definite(available_width),AvailableSpace::MinContent,diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rsindex d1896ad0a65..ed643841f74 100644--- a/crates/gpui/src/elements/text.rs+++ b/crates/gpui/src/elements/text.rs@@ -270,7 +270,7 @@ impl Element for &'static str {window: &mut Window,cx: &mut App,) -> (LayoutId, Self::RequestLayoutState) {- let mut state = TextLayout::default();+ let state = TextLayout::default();let layout_id = state.layout(SharedString::from(*self), None, window, cx);(layout_id, state)}@@ -344,7 +344,7 @@ impl Element for SharedString {window: &mut Window,cx: &mut App,) -> (LayoutId, Self::RequestLayoutState) {- let mut state = TextLayout::default();+ let state = TextLayout::default();let layout_id = state.layout(self.clone(), None, window, cx);(layout_id, state)}@@ -416,7 +416,7 @@ impl StyledText {/// Set the styling attributes for the given text, as well as/// as any ranges of text that have had their style customized.pub fn with_default_highlights(- mut self,+ self,default_style: &TextStyle,highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,) -> Self {@@ -860,7 +860,7 @@ impl TextLayout {}/// Get the byte index into the input of the pixel position.- pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {+ pub fn index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {let element_state = self.0.borrow();let element_state = element_state.as_ref()@@ -1169,7 +1169,7 @@ impl Element for InteractiveText {window.with_element_state::<InteractiveTextState, _>(global_id.unwrap(),|interactive_state, window| {- let mut interactive_state = interactive_state.unwrap_or_default();+ let interactive_state = interactive_state.unwrap_or_default();if let Some(click_listener) = self.click_listener.take() {let mouse_position = window.mouse_position();if let Ok(ix) = text_layout.index_for_position(mouse_position)@@ -1224,7 +1224,7 @@ impl Element for InteractiveText {}window.on_mouse_event({- let mut hover_listener = self.hover_listener.take();+ let hover_listener = self.hover_listener.take();let hitbox = hitbox.clone();let text_layout = text_layout.clone();let hovered_index = interactive_state.hovered_index.clone();diff --git a/crates/gpui/src/elements/uniform_list.rs b/crates/gpui/src/elements/uniform_list.rsindex 9ccad0bd1da..561292d4a30 100644--- a/crates/gpui/src/elements/uniform_list.rs+++ b/crates/gpui/src/elements/uniform_list.rs@@ -690,10 +690,10 @@ impl UniformList {}/// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.- pub fn y_flipped(mut self, y_flipped: bool) -> Self {+ pub fn y_flipped(self, y_flipped: bool) -> Self {if let Some(ref scroll_handle) = self.scroll_handle {let mut scroll_state = scroll_handle.0.borrow_mut();- let mut base_handle = &scroll_state.base_handle;+ let base_handle = &scroll_state.base_handle;let offset = base_handle.offset();match scroll_state.last_item_size {Some(last_size) if scroll_state.y_flipped != y_flipped => {diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rsindex 2328e954df3..dbb8386d063 100644--- a/crates/gpui/src/gpui.rs+++ b/crates/gpui/src/gpui.rs@@ -1,33 +1,43 @@#![doc = include_str!("../README.md")]#![warn(missing_docs)]#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks-#![allow(clippy::collapsible_else_if)] // False positives in platform specific code-#![allow(unused_mut)] // False positives in platform specific code++pub extern crate accesskit;+pub extern crate http_client;+#[cfg(any(test, feature = "test-support"))]+pub extern crate proptest;+/// Subsecond entry points for hot-patching callbacks outside GPUI's render boundaries.+#[cfg(all(+ feature = "hot-reload",+ any(+ target_os = "macos",+ target_os = "linux",+ target_os = "windows",+ target_os = "ios"+ )+))]+pub extern crate subsecond;extern crate self as gpui;++pub mod colors;+pub mod prelude;+pub mod profiler;+#[macro_use]mod action;mod app;-mod arena;mod asset_cache;mod assets;mod bounds_tree;mod color;-/// The default colors used by GPUI.-pub mod colors;-#[cfg(feature = "profiler")]-mod debug_overlay;mod element;mod elements;mod executor;-mod platform_scheduler;-pub(crate) use platform_scheduler::PlatformScheduler;mod geometry;mod gestures;mod global;-#[cfg(gpui_hot_reload)]-mod hot_reload;mod input;mod inspector;mod interactive;@@ -35,25 +45,8 @@ mod key_dispatch;mod keymap;mod path_builder;mod platform;-pub mod prelude;-/// Profiling utilities for task, frame, and thread performance tracking.-pub mod profiler;-#[cfg(any(- test,- target_os = "windows",- target_os = "linux",- target_family = "wasm",- feature = "test-support",- feature = "bench-support"-))]-#[expect(missing_docs)]-pub mod queue;-/// A seeded, mutable element tree for benchmarks and tests of GPUI rendering.-#[cfg(any(test, feature = "bench-support"))]-pub mod randomized_element_tree;+mod platform_scheduler;mod scene;-#[cfg(any(test, feature = "test-support", feature = "bench-support"))]-mod seeds;mod shared_uri;mod spring;mod style;@@ -62,18 +55,43 @@ mod subscription;mod svg_renderer;mod tab_stop;mod taffy;-#[cfg(any(test, feature = "test-support"))]-pub mod test;mod text_system;mod util;mod view;mod window;-#[cfg(any(test, feature = "test-support"))]-pub use proptest;+#[cfg(feature = "profiler")]+mod debug_overlay;+#[cfg(feature = "profiler")]+pub use debug_overlay::*;++#[cfg(gpui_hot_reload)]+mod hot_reload;+#[cfg(any(+ test,+ target_os = "windows",+ target_os = "linux",+ target_family = "wasm",+ feature = "test-support",+ feature = "bench-support"+))]+pub mod queue;++#[cfg(any(test, feature = "bench-support"))]+pub mod randomized_element_tree;++#[cfg(any(test, feature = "test-support", feature = "bench-support"))]+mod bench;+#[cfg(any(test, feature = "test-support", feature = "bench-support"))]+mod seeds;#[cfg(any(test, feature = "test-support", feature = "bench-support"))]pub use seeds::calculate_seeds;+#[cfg(any(test, feature = "test-support"))]+pub mod test;+#[cfg(any(test, feature = "test-support"))]+pub use test::*;+#[cfg(doc)]pub mod _accessibility;#[cfg(doc)]@@ -90,25 +108,16 @@ pub mod private {pub use serde_json;}-mod seal {- /// A mechanism for restricting implementations of a trait to only those in GPUI.- /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>- pub trait Sealed {}-}+#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]+pub use queue::{PriorityQueueReceiver, PriorityQueueSender};-pub use accesskit;-pub use accesskit::Action as AccessibleAction;-pub use accesskit::{Orientation, Role, Toggled};+pub use accesskit::{Action as AccessibleAction, Orientation, Role, Toggled};pub use action::*;pub use anyhow::Result;pub use app::*;-pub(crate) use arena::*;pub use asset_cache::*;pub use assets::*;pub use color::*;-pub use ctor::ctor;-#[cfg(feature = "profiler")]-pub use debug_overlay::*;pub use element::*;pub use elements::*;pub use executor::*;@@ -118,110 +127,24 @@ pub use global::*;pub use gpui_macros::{AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,};-pub use spring::*;--/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].-///-/// This mirrors `criterion::criterion_group!`, but the group measures with the-/// `gpui::BenchMeasurement` configured by `BENCH_MEASUREMENT` (see-/// `BenchMeasurement::from_env`). By default Criterion analyzes wall time-/// while retired instructions, cycles, IPC, context switches, and the other-/// counters this machine supports are printed per iteration in the GPUI bench-/// report. `BENCH_MEASUREMENT=instructions` makes Criterion analyze-/// process-wide instructions instead, `foreground-instructions` the benchmark-/// thread's alone, and `wall-time` disables all counters. A-/// `config = ...` expression may set any other Criterion option; its-/// measurement is replaced. To measure with something else, call-/// `criterion::criterion_group!` directly with-/// `config = criterion::Criterion::default().with_measurement(gpui::BenchMeasurement::new(...))`.-///-/// [`gpui::bench`]: crate::bench-#[macro_export]-macro_rules! bench_group {- (name = $name:ident; config = $config:expr; targets = $($target:path),+ $(,)?) => {- criterion::criterion_group! {- name = $name;- config = ($config).with_measurement($crate::BenchMeasurement::from_env_or_exit());- targets = $($target),+- }- };- ($name:ident, $($target:path),+ $(,)?) => {- $crate::bench_group! {- name = $name;- config = criterion::Criterion::default();- targets = $($target),+- }- };-}--/// Defines the entry point for GPUI Criterion benchmark groups.-///-/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the-/// same shape as ordinary Criterion benchmarks. It also installs-/// [`CountingAllocator`] as the binary's global allocator, so reports include-/// heap allocations per iteration. It wraps the system allocator by default;-/// `allocator = Path;` wraps another unit-struct allocator instead, e.g. to-/// compare allocators, which pay the same small counting cost:-///-/// ```ignore-/// gpui::bench_main!(allocator = mimalloc::MiMalloc; benches);-/// ```-///-/// `allocator = none;` installs no global allocator, leaving Rust's default and-/// dropping the allocation metrics from reports.-#[macro_export]-macro_rules! bench_main {- (allocator = none; $($groups:tt)*) => {- criterion::criterion_main!($($groups)*);- };- (allocator = $allocator:path; $($groups:tt)*) => {- #[global_allocator]- static GPUI_BENCH_ALLOCATOR: $crate::CountingAllocator<$allocator> =- $crate::CountingAllocator::new($allocator);-- criterion::criterion_main!($($groups)*);- };- ($($groups:tt)*) => {- $crate::bench_main!(allocator = ::std::alloc::System; $($groups)*);- };-}pub use gpui_shared_string::*;pub use gpui_util::arc_cow::ArcCow;-pub use http_client;pub use input::*;pub use inspector::*;pub use interactive::*;-use key_dispatch::*;pub use keymap::*;pub use path_builder::*;pub use platform::*;pub use profiler::*;-#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]-pub use queue::{PriorityQueueReceiver, PriorityQueueSender};pub use refineable::*;pub use scene::*;pub use shared_uri::*;-use std::{any::Any, future::Future};+pub use spring::*;pub use style::*;pub use styled::*;pub use subscription::*;-/// Subsecond entry points for hot-patching callbacks outside GPUI's render boundaries.-#[cfg(all(- feature = "hot-reload",- any(- target_os = "macos",- target_os = "linux",- target_os = "windows",- target_os = "ios"- )-))]-pub use subsecond;pub use svg_renderer::*;-pub(crate) use tab_stop::*;-use taffy::TaffyLayoutEngine;pub use taffy::{AvailableSpace, LayoutId};-#[cfg(any(test, feature = "test-support"))]-pub use test::*;pub use text_system::*;pub use util::{FutureExt, Timeout};pub use view::*;@@ -230,6 +153,20 @@ pub use window::*;#[cfg(not(target_family = "wasm"))]pub use pollster::block_on;+pub(crate) use arena::*;+pub(crate) use platform_scheduler::PlatformScheduler;+pub(crate) use tab_stop::*;++use std::{any::Any, future::Future};++use key_dispatch::*;++mod seal {+ /// A mechanism for restricting implementations of a trait to only those in GPUI.+ /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>+ pub trait Sealed {}+}+/// The context trait, allows the different contexts in GPUI to be used/// interchangeably for certain operations.pub trait AppContext {diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rsindex 1e7a4244725..e4bce617277 100644--- a/crates/gpui/src/key_dispatch.rs+++ b/crates/gpui/src/key_dispatch.rs@@ -586,7 +586,7 @@ impl DispatchTree {}pub fn view_path_reversed(&self, view_id: EntityId) -> impl Iterator<Item = EntityId> {- let mut current_node_id = self.view_node_ids.get(&view_id).copied();+ let current_node_id = self.view_node_ids.get(&view_id).copied();std::iter::successors(current_node_id.map(|node_id| self.node(node_id)),diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rsindex b5c081009a8..7b20738889c 100644--- a/crates/gpui/src/platform/test/platform.rs+++ b/crates/gpui/src/platform/test/platform.rs@@ -83,7 +83,7 @@ impl ScreenCaptureSource for TestScreenCaptureSource {_foreground_executor: &ForegroundExecutor,_frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {- let (mut tx, rx) = oneshot::channel();+ let (tx, rx) = oneshot::channel();let stream = TestScreenCaptureStream {};tx.send(Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>)).ok();@@ -573,7 +573,7 @@ impl Platform for TestPlatform {fn screen_capture_sources(&self,) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {- let (mut tx, rx) = oneshot::channel();+ let (tx, rx) = oneshot::channel();tx.send(Ok(self.screen_capture_sources.borrow()diff --git a/crates/gpui/src/profiler.rs b/crates/gpui/src/profiler.rsindex ea1cd5ae1df..d78ccb9de81 100644--- a/crates/gpui/src/profiler.rs+++ b/crates/gpui/src/profiler.rs@@ -1,3 +1,5 @@+//! Profiling utilities for task, frame, and thread performance tracking.+#[cfg(feature = "profiler")]use hdrhistogram::Histogram;use itertools::Itertools;@@ -368,7 +370,7 @@ impl ProfilingCollector {let buffer_len = thread.timings.len() as u64;let buffer_start = thread.total_pushed.saturating_sub(buffer_len);- let mut slice = if prev_cursor < buffer_start {+ let slice = if prev_cursor < buffer_start {// Cursor fell behind the buffer — some entries were evicted.// Return everything still in the buffer.thread.timings.as_slice()diff --git a/crates/gpui/src/profiler/hang.rs b/crates/gpui/src/profiler/hang.rsindex 386bd20801f..16ef408783c 100644--- a/crates/gpui/src/profiler/hang.rs+++ b/crates/gpui/src/profiler/hang.rs@@ -664,7 +664,7 @@ mod tests {use crate::{self as gpui, AnyView, AppContext as _, Context, FocusHandle, InteractiveElement,IntoElement, Modifiers, MouseButton, ParentElement as _, Render, Styled, TestAppContext,- VisualTestContext, Window, WindowId, div, point, px,+ VisualTestContext, Window, WindowId, actions, div, point, px,};use crate::profiler::{diff --git a/crates/gpui/src/profiler/journal.rs b/crates/gpui/src/profiler/journal.rsindex 97d88852d7b..39df15d5173 100644--- a/crates/gpui/src/profiler/journal.rs+++ b/crates/gpui/src/profiler/journal.rs@@ -1712,7 +1712,7 @@ mod tests {cx.update(|cx| {cx.system_wake_observers.clone()- .retain(&(), |callback| callback(cx))+ .retain(|callback| callback(cx))});cx.run_until_parked();handlediff --git a/crates/gpui/src/queue.rs b/crates/gpui/src/queue.rsindex 6d921309cba..6848ce86737 100644--- a/crates/gpui/src/queue.rs+++ b/crates/gpui/src/queue.rs@@ -1,3 +1,8 @@+//! Provides a thread-safe queue with weighted random selection between priorities.+//!+//! Items within each priority are received in FIFO order. Receivers can be cloned+//! to share work, and queued items remain available after the sender is dropped.+use std::{collections::VecDeque,fmt,@@ -145,11 +150,29 @@ impl<T> PriorityQueueSender<T> {Self { state }}+ /// Enqueues an item at the given priority, waiting for the queue lock if necessary.+ ///+ /// # Errors+ ///+ /// Returns the item in a [`SendError<T>`] if all receivers have been dropped.+ ///+ /// # Panics+ ///+ /// Panics if `priority` is [`Priority::RealtimeAudio`] and a receiver still exists.pub fn send(&self, priority: Priority, item: T) -> Result<(), SendError<T>> {self.state.send(priority, item)?;Ok(())}+ /// Enqueues an item at the given priority, spinning until the queue lock is acquired.+ ///+ /// # Errors+ ///+ /// Returns the item in a [`SendError<T>`] if all receivers have been dropped.+ ///+ /// # Panics+ ///+ /// Panics if `priority` is [`Priority::RealtimeAudio`] and a receiver still exists.pub fn spin_send(&self, priority: Priority, item: T) -> Result<(), SendError<T>> {self.state.spin_send(priority, item)?;Ok(())@@ -214,6 +237,17 @@ pub struct RecvError;#[allow(dead_code)]impl<T> PriorityQueueReceiver<T> {+ /// Creates an empty priority queue and returns its sender and receiver.+ ///+ /// # Examples+ ///+ /// ```+ /// use gpui::{Priority, queue::PriorityQueueReceiver};+ ///+ /// let (sender, mut receiver) = PriorityQueueReceiver::new();+ /// sender.send(Priority::Medium, 42).unwrap();+ /// assert_eq!(receiver.pop().unwrap(), 42);+ /// ```pub fn new() -> (PriorityQueueSender<T>, Self) {let state = PriorityQueueState {queues: Mutex::new(PriorityQueues {@@ -271,6 +305,14 @@ impl<T> PriorityQueueReceiver<T> {self.pop_inner(false)}+ /// Pops an item if available, spinning until the queue lock is acquired.+ ///+ /// Returns `Ok(None)` if the queue is empty and the sender still exists.+ /// Does not wait for new items to arrive.+ ///+ /// # Errors+ ///+ /// Returns [`RecvError`] if the queue is empty and the sender has been dropped.pub fn spin_try_pop(&mut self) -> Result<Option<T>, RecvError> {use Priority as P;@@ -312,7 +354,7 @@ impl<T> PriorityQueueReceiver<T> {/// Pops an element from the priority queue blocking if necessary.////// This method is best suited if you only intend to pop one element, for better performance- /// on large queues see [`Self::iter``]+ /// on large queues see [`Self::iter`].////// # Errors///@@ -469,7 +511,7 @@ mod tests {#[test]fn all_tasks_get_yielded() {- let (tx, mut rx) = PriorityQueueReceiver::new();+ let (tx, rx) = PriorityQueueReceiver::new();tx.send(Priority::Medium, 20).unwrap();tx.send(Priority::High, 30).unwrap();tx.send(Priority::Low, 10).unwrap();diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rsindex 0325769068d..b483cb7efa8 100644--- a/crates/gpui/src/randomized_element_tree.rs+++ b/crates/gpui/src/randomized_element_tree.rs@@ -1,3 +1,4 @@+//! A seeded, mutable element tree for benchmarks and tests of GPUI rendering.use crate::{AnyElement, AppContext as _, Context, ElementId, Entity, Hsla, InteractiveElement, IntoElement,ParentElement, Render, StatefulInteractiveElement, Styled, Window, div, px,diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rsindex 6cb33874b23..a4116aa5251 100644--- a/crates/gpui/src/scene.rs+++ b/crates/gpui/src/scene.rs@@ -625,7 +625,7 @@ impl TransformationMatrix {}/// Move the origin by a given point- pub fn translate(mut self, point: Point<ScaledPixels>) -> Self {+ pub fn translate(self, point: Point<ScaledPixels>) -> Self {self.compose(Self {rotation_scale: [[1.0, 0.0], [0.0, 1.0]],translation: [point.x.0, point.y.0],diff --git a/crates/gpui/src/style.rs b/crates/gpui/src/style.rsindex 9150fdded91..323c79e004f 100644--- a/crates/gpui/src/style.rs+++ b/crates/gpui/src/style.rs@@ -1347,7 +1347,7 @@ mod tests {"Combining empty styles should not produce a non-empty style.");- let mut style_b = HighlightStyle {+ let style_b = HighlightStyle {color: Some(red()),strikethrough: Some(StrikethroughStyle {thickness: px(2.),@@ -1377,7 +1377,7 @@ mod tests {"Blending a style with an empty style should not change the style.");- let mut style_c = expected_style;+ let style_c = expected_style;let style_d = HighlightStyle {color: Some(blue().alpha(0.7)),diff --git a/crates/gpui/src/styled.rs b/crates/gpui/src/styled.rsindex a24982a6acb..aa77a20a447 100644--- a/crates/gpui/src/styled.rs+++ b/crates/gpui/src/styled.rs@@ -120,30 +120,30 @@ pub trait Styled: Sized {}/// Sets the text alignment to left- fn text_left(mut self) -> Self {+ fn text_left(self) -> Self {self.text_align(TextAlign::Left)}/// Sets the text alignment to center- fn text_center(mut self) -> Self {+ fn text_center(self) -> Self {self.text_align(TextAlign::Center)}/// Sets the text alignment to right- fn text_right(mut self) -> Self {+ fn text_right(self) -> Self {self.text_align(TextAlign::Right)}/// Sets the truncate to prevent text from wrapping and truncate overflowing text with an ellipsis (…) if needed./// [Docs](https://tailwindcss.com/docs/text-overflow#truncate)- fn truncate(mut self) -> Self {+ fn truncate(self) -> Self {self.overflow_hidden().whitespace_nowrap().text_ellipsis()}/// Sets number of lines to show before truncating the text./// [Docs](https://tailwindcss.com/docs/line-clamp)fn line_clamp(mut self, lines: usize) -> Self {- let mut text_style = self.text_style();+ let text_style = self.text_style();text_style.line_clamp = Some(lines);self.overflow_hidden()}diff --git a/crates/gpui/src/subscription.rs b/crates/gpui/src/subscription.rsindex b0c55a39661..6bd455e5f39 100644--- a/crates/gpui/src/subscription.rs+++ b/crates/gpui/src/subscription.rs@@ -3,9 +3,14 @@ use gpui_util::post_inc;use std::{cell::{Cell, RefCell},fmt::Debug,+ mem,rc::Rc,};+/// Stores subscriptions for a single emitter.+pub(crate) struct SingleSubscriberSet<Callback>(Rc<RefCell<SingleSubscriberSetState<Callback>>>);++/// Stores subscriptions for emitters.pub(crate) struct SubscriberSet<EmitterKey, Callback>(Rc<RefCell<SubscriberSetState<EmitterKey, Callback>>>,);@@ -17,13 +22,19 @@ impl<EmitterKey, Callback> Clone for SubscriberSet<EmitterKey, Callback> {}struct SubscriberSetState<EmitterKey, Callback> {- subscribers: BTreeMap<EmitterKey, Option<BTreeMap<usize, Subscriber<Callback>>>>,+ subscribers: BTreeMap<EmitterKey, BTreeMap<usize, Subscriber<Callback>>>,next_subscriber_id: usize,}+#[derive(Clone, Copy, PartialEq, Eq)]+enum SubscriberState {+ Pending,+ Active,+ Dropped,+}+struct Subscriber<Callback> {- active: Rc<Cell<bool>>,- dropped: Rc<Cell<bool>>,+ state: Rc<Cell<SubscriberState>>,callback: Callback,}@@ -39,43 +50,47 @@ where})))}- /// Inserts a new [`Subscription`] for the given `emitter_key`. By default, subscriptions- /// are inert, meaning that they won't be listed when calling `[SubscriberSet::remove]` or `[SubscriberSet::retain]`.- /// This method returns a tuple of a [`Subscription`] and an `impl FnOnce`, and you can use the latter- /// to activate the [`Subscription`].- pub fn insert(+ /// Inserts an immediately active subscription for the given emitter.+ pub fn insert(&self, emitter_key: EmitterKey, callback: Callback) -> Subscription {+ let (subscription, activate) = self.insert_pending(emitter_key, callback);+ activate();+ subscription+ }++ /// Inserts a pending subscription and returns its handle and activation function.+ ///+ /// Pending callbacks are skipped by `retain` and excluded from `remove` until activated.+ pub fn insert_pending(&self,emitter_key: EmitterKey,callback: Callback,) -> (Subscription, impl FnOnce() + use<EmitterKey, Callback>) {- let active = Rc::new(Cell::new(false));- let dropped = Rc::new(Cell::new(false));+ let state = Rc::new(Cell::new(SubscriberState::Pending));let mut lock = self.0.borrow_mut();let subscriber_id = post_inc(&mut lock.next_subscriber_id);lock.subscribers.entry(emitter_key.clone()).or_default()- .get_or_insert_with(Default::default).insert(subscriber_id,Subscriber {- active: active.clone(),- dropped: dropped.clone(),+ state: state.clone(),callback,},);let this = self.0.clone();let subscription = Subscription {- unsubscribe: Some(Box::new(move || {- dropped.set(true);+ unsubscribe: Some(Box::new({+ let state = state.clone();+ move || {+ state.set(SubscriberState::Dropped);- let mut lock = this.borrow_mut();- let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else {- return;- };+ let mut lock = this.borrow_mut();+ let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else {+ return;+ };- if let Some(subscribers) = subscribers {subscribers.remove(&subscriber_id);if subscribers.is_empty() {lock.subscribers.remove(&emitter_key);@@ -83,7 +98,11 @@ where}})),};- (subscription, move || active.set(true))+ (subscription, move || {+ if state.get() == SubscriberState::Pending {+ state.set(SubscriberState::Active);+ }+ })}pub fn remove(@@ -92,12 +111,11 @@ where) -> impl IntoIterator<Item = Callback> + use<EmitterKey, Callback> {let subscribers = self.0.borrow_mut().subscribers.remove(emitter);subscribers- .unwrap_or_default().map(|s| s.into_values()).into_iter().flatten().filter_map(|subscriber| {- if subscriber.active.get() {+ if subscriber.state.get() == SubscriberState::Active {Some(subscriber.callback)} else {None@@ -111,35 +129,129 @@ wherewhereF: FnMut(&mut Callback) -> bool,{+ // We do not remove here upfront to reduce BTreeMap shuffling churnlet Some(mut subscribers) = self.0.borrow_mut().subscribers.get_mut(emitter)- .and_then(|s| s.take())+ .map(mem::take)else {return;};- subscribers.retain(|_, subscriber| {- if !subscriber.active.get() {- return true;- }- if subscriber.dropped.get() {- return false;- }- let keep = f(&mut subscriber.callback);- keep && !subscriber.dropped.get()- });+ subscribers.retain(|_, subscriber| subscriber.retain(&mut f));let mut lock = self.0.borrow_mut();- // Add any new subscribers that were added while invoking the callback.- if let Some(Some(new_subscribers)) = lock.subscribers.remove(emitter) {- subscribers.extend(new_subscribers);+ if subscribers.is_empty() {+ if lock+ .subscribers+ .get(emitter)+ .is_some_and(|subscribers| subscribers.is_empty())+ {+ lock.subscribers.remove(emitter);+ }+ return;}- if !subscribers.is_empty() {- lock.subscribers.insert(emitter.clone(), Some(subscribers));+ // Add any new subscribers that were added while invoking the callback.+ lock.subscribers+ .entry(emitter.clone())+ .or_default()+ .append(&mut subscribers);+ }+}++struct SingleSubscriberSetState<Callback> {+ subscribers: BTreeMap<usize, Subscriber<Callback>>,+ next_subscriber_id: usize,+}++impl<Callback> Clone for SingleSubscriberSet<Callback> {+ fn clone(&self) -> Self {+ Self(self.0.clone())+ }+}++impl<Callback: 'static> SingleSubscriberSet<Callback> {+ pub fn new() -> Self {+ Self(Rc::new(RefCell::new(SingleSubscriberSetState {+ subscribers: BTreeMap::new(),+ next_subscriber_id: 0,+ })))+ }++ /// Inserts an immediately active subscription.+ pub fn insert(&self, callback: Callback) -> Subscription {+ let (subscription, activate) = self.insert_pending(callback);+ activate();+ subscription+ }++ /// Inserts a pending subscription and returns its handle and activation function.+ ///+ /// Pending callbacks are skipped by `retain` and excluded from `remove` until activated.+ pub fn insert_pending(+ &self,+ callback: Callback,+ ) -> (Subscription, impl FnOnce() + use<Callback>) {+ let state = Rc::new(Cell::new(SubscriberState::Pending));+ let mut lock = self.0.borrow_mut();+ let subscriber_id = post_inc(&mut lock.next_subscriber_id);+ lock.subscribers.insert(+ subscriber_id,+ Subscriber {+ state: state.clone(),+ callback,+ },+ );+ let this = self.0.clone();++ let subscription = Subscription {+ unsubscribe: Some(Box::new({+ let state = state.clone();+ move || {+ state.set(SubscriberState::Dropped);+ this.borrow_mut().subscribers.remove(&subscriber_id);+ }+ })),+ };+ (subscription, move || {+ if state.get() == SubscriberState::Pending {+ state.set(SubscriberState::Active);+ }+ })+ }++ /// Removes all subscriptions and returns the active callbacks in registration order.+ pub fn remove(&self) -> impl IntoIterator<Item = Callback> + use<Callback> {+ let subscribers = mem::take(&mut self.0.borrow_mut().subscribers);+ subscribers.into_values().filter_map(|subscriber| {+ if subscriber.state.get() == SubscriberState::Active {+ Some(subscriber.callback)+ } else {+ None+ }+ })+ }++ /// Invokes each active callback, removing subscriptions for which `f` returns false.+ pub fn retain(&self, mut f: impl FnMut(&mut Callback) -> bool) {+ let mut subscribers = mem::take(&mut self.0.borrow_mut().subscribers);+ subscribers.retain(|_, subscriber| subscriber.retain(&mut f));+ self.0.borrow_mut().subscribers.append(&mut subscribers);+ }+}++impl<Callback> Subscriber<Callback> {+ fn retain(&mut self, f: &mut impl FnMut(&mut Callback) -> bool) -> bool {+ match self.state.get() {+ SubscriberState::Pending => true,+ SubscriberState::Dropped => false,+ SubscriberState::Active => {+ let keep = f(&mut self.callback);+ keep && self.state.get() != SubscriberState::Dropped+ }}}}@@ -204,6 +316,102 @@ mod tests {use super::*;use crate::{Global, TestApp};+ #[test]+ fn test_immediate_and_pending_insertions() {+ let subscribers = SubscriberSet::new();+ let first = subscribers.insert(1usize, 10);+ let (second, activate_second) = subscribers.insert_pending(1, 20);+ let mut visited = Vec::new();+ subscribers.retain(&1, |callback| {+ visited.push(*callback);+ subscribers.insert(1, 30).detach();+ true+ });+ assert_eq!(visited, [10]);+ activate_second();+ assert_eq!(+ subscribers.remove(&1).into_iter().collect::<Vec<_>>(),+ [10, 20, 30]+ );+ drop(first);+ drop(second);++ let (pending, _activate) = subscribers.insert_pending(1, 40);+ assert_eq!(subscribers.remove(&1).into_iter().count(), 0);+ drop(pending);+ }++ #[test]+ fn test_single_immediate_and_pending_insertions() {+ let subscribers = SingleSubscriberSet::new();+ let first = subscribers.insert(10);+ let (second, activate_second) = subscribers.insert_pending(20);+ let mut visited = Vec::new();+ subscribers.retain(|callback| {+ visited.push(*callback);+ subscribers.insert(30).detach();+ true+ });+ assert_eq!(visited, [10]);+ activate_second();+ assert_eq!(+ subscribers.remove().into_iter().collect::<Vec<_>>(),+ [10, 20, 30]+ );+ drop(first);+ drop(second);++ let (pending, _activate) = subscribers.insert_pending(40);+ assert_eq!(subscribers.remove().into_iter().count(), 0);+ drop(pending);+ }++ #[test]+ fn test_activation_after_drop_during_retain() {+ let subscribers = SubscriberSet::new();+ let (first, activate_first) = subscribers.insert_pending(1usize, 10);+ let (second, activate_second) = subscribers.insert_pending(1, 20);+ subscribers.retain(&1, |_| panic!("pending subscriber invoked"));+ activate_first();+ let mut second = Some((second, activate_second));+ let mut visited = Vec::new();++ subscribers.retain(&1, |callback| {+ visited.push(*callback);+ let (subscription, activate) = second.take().expect("only the first callback runs");+ drop(subscription);+ activate();+ true+ });++ assert_eq!(visited, [10]);+ assert_eq!(subscribers.remove(&1).into_iter().collect::<Vec<_>>(), [10]);+ drop(first);+ }++ #[test]+ fn test_single_activation_after_drop_during_retain() {+ let subscribers = SingleSubscriberSet::new();+ let (first, activate_first) = subscribers.insert_pending(10);+ let (second, activate_second) = subscribers.insert_pending(20);+ subscribers.retain(|_| panic!("pending subscriber invoked"));+ activate_first();+ let mut second = Some((second, activate_second));+ let mut visited = Vec::new();++ subscribers.retain(|callback| {+ visited.push(*callback);+ let (subscription, activate) = second.take().expect("only the first callback runs");+ drop(subscription);+ activate();+ true+ });++ assert_eq!(visited, [10]);+ assert_eq!(subscribers.remove().into_iter().collect::<Vec<_>>(), [10]);+ drop(first);+ }+#[test]fn test_unsubscribe_during_callback_with_insert() {struct TestGlobal;diff --git a/crates/gpui/src/svg_renderer.rs b/crates/gpui/src/svg_renderer.rsindex 798fb2a9657..49f77a170dc 100644--- a/crates/gpui/src/svg_renderer.rs+++ b/crates/gpui/src/svg_renderer.rs@@ -480,7 +480,7 @@ mod tests {#[test]fn test_select_emoji_font_skips_family_without_glyph() {- let mut db = db_with_bundled_fonts();+ let db = db_with_bundled_fonts();let ibm_plex_sans = db.query(&usvg::fontdb::Query {diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rsindex 8a1738a3c8a..593c3b8668e 100644--- a/crates/gpui/src/text_system.rs+++ b/crates/gpui/src/text_system.rs@@ -25,12 +25,11 @@ use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};use smallvec::{SmallVec, smallvec};use std::{borrow::Cow,- cell::RefCell,+ cell::Cell,cmp,collections::VecDeque,fmt::{Debug, Display, Formatter},hash::{Hash, Hasher},- mem,ops::{Deref, DerefMut, Range},sync::{Arc,@@ -634,7 +633,7 @@ impl TextSystem {#[derive(Deref)]pub struct WindowTextSystem {line_layout_cache: LineLayoutCache,- font_runs_buffer: RefCell<Vec<FontRun>>,+ font_runs_buffer: Cell<Vec<FontRun>>,#[deref]text_system: Arc<TextSystem>,}@@ -647,7 +646,7 @@ impl WindowTextSystem {text_system.platform_text_system.clone(),text_system.font_generation.clone(),),- font_runs_buffer: RefCell::default(),+ font_runs_buffer: Cell::default(),text_system,}}@@ -723,10 +722,10 @@ 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 = mem::take(&mut *self.font_runs_buffer.borrow_mut());+ let mut font_runs = self.font_runs_buffer.take();let mut lines = SmallVec::new();- let mut max_wrap_lines = line_clamp;+ let max_wrap_lines = line_clamp;let mut wrapped_lines = 0;let mut process_line = |line_text: SharedString, line_start, line_end| {@@ -837,7 +836,7 @@ impl WindowTextSystem {process_line(text, 0, end);}- *self.font_runs_buffer.borrow_mut() = font_runs;+ self.font_runs_buffer.set(font_runs);Ok(lines)}@@ -858,7 +857,7 @@ impl WindowTextSystem {force_width: Option<Pixels>,) -> Arc<LineLayout> {let mut last_run = None::<&TextRun>;- let mut font_runs = mem::take(&mut *self.font_runs_buffer.borrow_mut());+ let mut font_runs = self.font_runs_buffer.take();font_runs.clear();for run in runs.iter() {@@ -896,7 +895,7 @@ impl WindowTextSystem {force_width,);- *self.font_runs_buffer.borrow_mut() = font_runs;+ self.font_runs_buffer.set(font_runs);layout}diff --git a/crates/gpui/src/text_system/line.rs b/crates/gpui/src/text_system/line.rsindex f5210052e2b..56917821511 100644--- a/crates/gpui/src/text_system/line.rs+++ b/crates/gpui/src/text_system/line.rs@@ -899,7 +899,7 @@ fn paint_line_background(}if let Some((mut background_origin, background_color)) = finished_background {- let mut width = glyph_origin.x - background_origin.x;+ let width = glyph_origin.x - background_origin.x;if background_origin.x == glyph_origin.x {background_origin.x -= max_glyph_size.width.half();};diff --git a/crates/gpui/src/text_system/line_layout.rs b/crates/gpui/src/text_system/line_layout.rsindex 26a202f0144..1fcbec7f52c 100644--- a/crates/gpui/src/text_system/line_layout.rs+++ b/crates/gpui/src/text_system/line_layout.rs@@ -368,7 +368,7 @@ impl WrappedLineLayout {fn _index_for_position(&self,- mut position: Point<Pixels>,+ position: Point<Pixels>,line_height: Pixels,closest: bool,) -> Result<usize, usize> {@@ -427,7 +427,7 @@ impl WrappedLineLayout {/// Returns the pixel position for the given byte index.pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {let mut line_start_ix = 0;- let mut line_end_indices = self+ let line_end_indices = self.wrap_boundaries.iter().map(|wrap_boundary| {diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex a3b1b1b66c7..006692dcc92 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -4,6 +4,8 @@ use crate::DebugFrameOverlayMode;use crate::Inspector;#[cfg(feature = "profiler")]use crate::profiler;+use crate::subscription::SingleSubscriberSet;+use crate::taffy::TaffyLayoutEngine;use crate::{Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,@@ -17,12 +19,12 @@ use crate::{PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,- StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,- SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration,- TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,- TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,- WindowBounds, WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams,- WindowTextSystem, WindowVisibility, point, prelude::*, px, rems, size, transparent_black,+ StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab,+ SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, TextInputStateChange,+ TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, TransformationMatrix,+ Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds,+ WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, WindowTextSystem,+ WindowVisibility, point, prelude::*, px, rems, size, transparent_black,};use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};@@ -830,7 +832,7 @@ impl HitboxId {window.mouse_hit_test.ids.contains(&self)}- fn next(mut self) -> HitboxId {+ fn next(self) -> HitboxId {HitboxId(self.0.wrapping_add(1))}}@@ -1227,7 +1229,7 @@ pub struct Window {pub(crate) removed: bool,pub(crate) platform_window: Box<dyn PlatformWindow>,pub(crate) display_id: Option<DisplayId>,- pub(crate) display_observers: SubscriberSet<(), AnyObserver>,+ pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,is_resizable: bool,is_minimizable: bool,sprite_atlas: Arc<dyn PlatformAtlas>,@@ -1262,8 +1264,8 @@ pub struct Window {pub(crate) tooltip_bounds: Option<TooltipBounds>,pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,pub(crate) dirty_views: FxHashSet<EntityId>,- focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,- pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,+ focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,+ pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,focus_lost_path: SmallVec<[FocusId; 8]>,default_prevented: bool,mouse_position: Point<Pixels>,@@ -1271,14 +1273,14 @@ pub struct Window {modifiers: Modifiers,capslock: Capslock,scale_factor: f32,- pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,+ pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,appearance: WindowAppearance,- pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,- pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,+ pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,+ pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,active: Rc<Cell<bool>>,visibility: WindowVisibility,pub(crate) visibility_observers:- SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,+ SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,hovered: Rc<Cell<bool>>,pub(crate) needs_present: Rc<Cell<bool>>,/// Tracks recent input event timestamps to determine if input is arriving at a high rate.@@ -1292,7 +1294,7 @@ pub struct Window {long_press_timer: Option<Task<()>>,long_press_capture: Option<EntityId>,pub(crate) refreshing: bool,- pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,+ pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,pub(crate) focus: Option<FocusId>,focus_enabled: bool,/// Incremented every time focus moves. Used to invalidate a@@ -1300,7 +1302,7 @@ pub struct Window {pub(crate) focus_generation: u64,pending_input: Option<PendingInput>,pending_modifier: ModifierState,- pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,+ pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,prompt: Option<RenderablePromptHandle>,pub(crate) client_inset: Option<Pixels>,/// The hitbox that has captured the pointer, if any.@@ -2029,7 +2031,7 @@ impl Window {window.activation_observers.clone()- .retain(&(), |callback| callback(window, cx));+ .retain(|callback| callback(window, cx));window.bounds_changed(cx);window.refresh();@@ -2149,7 +2151,7 @@ impl Window {removed: false,platform_window,display_id,- display_observers: SubscriberSet::new(),+ display_observers: SingleSubscriberSet::new(),is_resizable,is_minimizable,sprite_atlas,@@ -2176,8 +2178,8 @@ impl Window {next_tooltip_id: TooltipId::default(),tooltip_bounds: None,dirty_views: FxHashSet::default(),- focus_listeners: SubscriberSet::new(),- focus_lost_listeners: SubscriberSet::new(),+ focus_listeners: SingleSubscriberSet::new(),+ focus_lost_listeners: SingleSubscriberSet::new(),focus_lost_path: SmallVec::new(),default_prevented: true,mouse_position,@@ -2185,13 +2187,13 @@ impl Window {modifiers,capslock,scale_factor,- bounds_observers: SubscriberSet::new(),+ bounds_observers: SingleSubscriberSet::new(),appearance,- appearance_observers: SubscriberSet::new(),- button_layout_observers: SubscriberSet::new(),+ appearance_observers: SingleSubscriberSet::new(),+ button_layout_observers: SingleSubscriberSet::new(),active,visibility,- visibility_observers: SubscriberSet::new(),+ visibility_observers: SingleSubscriberSet::new(),hovered,needs_present,input_rate_tracker,@@ -2207,13 +2209,13 @@ impl Window {long_press_timer: None,long_press_capture: None,refreshing: false,- activation_observers: SubscriberSet::new(),+ activation_observers: SingleSubscriberSet::new(),focus: None,focus_enabled: true,focus_generation: 0,pending_input: None,pending_modifier: ModifierState::default(),- pending_input_observers: SubscriberSet::new(),+ pending_input_observers: SingleSubscriberSet::new(),prompt: None,client_inset: None,image_cache_stack: Vec::new(),@@ -2234,7 +2236,7 @@ impl Window {&self,value: AnyWindowFocusListener,) -> (Subscription, impl FnOnce() + use<>) {- self.focus_listeners.insert((), value)+ self.focus_listeners.insert_pending(value)}}@@ -2293,7 +2295,7 @@ impl Window {profiler::journal::record_window_visibility(self.handle.window_id(), visibility);self.visibility_observers.clone()- .retain(&(), |callback| callback(visibility, self, cx));+ .retain(|callback| callback(visibility, self, cx));}#[cfg(feature = "profiler")]if self.invalidator.is_dirty() || self.needs_present.get() {@@ -2321,15 +2323,11 @@ impl Window {&self,mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,) -> Subscription {- let (subscription, activate) = self.visibility_observers.insert(- (),- Box::new(move |visibility, window, cx| {+ self.visibility_observers+ .insert(Box::new(move |visibility, window, cx| {callback(visibility, window, cx);true- }),- );- activate();- subscription+ }))}/// Registers a callback to be invoked when the window appearance changes.@@ -2337,15 +2335,11 @@ impl Window {&self,mut callback: impl FnMut(&mut Window, &mut App) + 'static,) -> Subscription {- let (subscription, activate) = self.appearance_observers.insert(- (),- Box::new(move |window, cx| {+ self.appearance_observers+ .insert(Box::new(move |window, cx| {callback(window, cx);true- }),- );- activate();- subscription+ }))}/// Registers a callback to be invoked when the window button layout changes.@@ -2353,15 +2347,11 @@ impl Window {&self,mut callback: impl FnMut(&mut Window, &mut App) + 'static,) -> Subscription {- let (subscription, activate) = self.button_layout_observers.insert(- (),- Box::new(move |window, cx| {+ self.button_layout_observers+ .insert(Box::new(move |window, cx| {callback(window, cx);true- }),- );- activate();- subscription+ }))}/// Replaces the root entity of the window with a new one.@@ -2587,7 +2577,7 @@ impl Window {context_stack: Vec<KeyContext>,cx: &mut App,) {- cx.keystroke_observers.clone().retain(&(), move |callback| {+ cx.keystroke_observers.clone().retain(move |callback| {(callback)(&KeystrokeEvent {keystroke: keystroke.clone(),@@ -2608,20 +2598,18 @@ impl Window {context_stack: Vec<KeyContext>,cx: &mut App,) {- cx.keystroke_interceptors- .clone()- .retain(&(), move |callback| {- (callback)(- &KeystrokeEvent {- keystroke: keystroke.clone(),- input_preference,- action: None,- context_stack: context_stack.clone(),- },- self,- cx,- )- });+ cx.keystroke_interceptors.clone().retain(move |callback| {+ (callback)(+ &KeystrokeEvent {+ keystroke: keystroke.clone(),+ input_preference,+ action: None,+ context_stack: context_stack.clone(),+ },+ self,+ cx,+ )+ });}/// Schedules the given function to be run at the end of the current effect cycle, allowing entities@@ -2704,22 +2692,20 @@ impl Window {&self,entity: &Entity<T>,cx: &mut App,- mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,+ on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,) -> SubscriptionwhereT: 'static,{let entity_id = entity.entity_id();let window_handle = self.handle;- let (subscription, activate) = cx.release_listeners.insert(+ cx.release_listeners.insert(entity_id,Box::new(move |entity, cx| {let entity = entity.downcast_mut().expect("invalid entity type");let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));}),- );- activate();- subscription+ )}/// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across@@ -2819,7 +2805,7 @@ impl Window {self.bounds_observers.clone()- .retain(&(), |callback| callback(self, cx));+ .retain(|callback| callback(self, cx));}fn display_changed(handle: AnyWindowHandle, cx: &mut App) {@@ -2851,7 +2837,7 @@ impl Window {pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {self.display_observers.clone()- .retain(&(), |callback| callback(self, cx));+ .retain(|callback| callback(self, cx));}/// The time between refreshes of the display the window is on, as of the@@ -2870,15 +2856,10 @@ impl Window {&self,mut callback: impl FnMut(&mut Window, &mut App) + 'static,) -> Subscription {- let (subscription, activate) = self.display_observers.insert(- (),- Box::new(move |window, cx| {- callback(window, cx);- true- }),- );- activate();- subscription+ self.display_observers.insert(Box::new(move |window, cx| {+ callback(window, cx);+ true+ }))}/// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.@@ -2937,13 +2918,13 @@ impl Window {self.appearance_observers.clone()- .retain(&(), |callback| callback(self, cx));+ .retain(|callback| callback(self, cx));}pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {self.button_layout_observers.clone()- .retain(&(), |callback| callback(self, cx));+ .retain(|callback| callback(self, cx));}/// Returns the appearance of the current window.@@ -3551,7 +3532,7 @@ impl Window {self.focus_lost_path = previous_focus_path.clone();self.focus_lost_listeners.clone()- .retain(&(), |listener| listener(self, cx));+ .retain(|listener| listener(self, cx));self.focus_lost_path = SmallVec::new();// The focus-lost fallback (e.g. a workspace refocusing itself) may target// an element that isn't part of the element tree, in which case scheduling@@ -3574,7 +3555,7 @@ impl Window {};self.focus_listeners.clone()- .retain(&(), |listener| listener(&event, self, cx));+ .retain(|listener| listener(&event, self, cx));}debug_assert!(self.rendered_entity_stack.is_empty());@@ -3976,7 +3957,7 @@ impl Window {let traversal_order = self.deferred_draw_traversal_order();let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);for deferred_draw_ix in traversal_order {- let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];+ let deferred_draw = &mut deferred_draws[deferred_draw_ix];self.element_id_stack.clone_from(&deferred_draw.element_id_stack);self.next_frame@@ -5012,7 +4993,7 @@ impl Window {&mut self,bounds: Bounds<Pixels>,path: SharedString,- mut data: Option<&[u8]>,+ data: Option<&[u8]>,transformation: TransformationMatrix,color: Hsla,cx: &App,@@ -5324,7 +5305,7 @@ impl Window {self.invalidator.debug_assert_prepaint();let content_mask = self.content_mask();- let mut id = self.next_hitbox_id;+ let id = self.next_hitbox_id;self.next_hitbox_id = self.next_hitbox_id.next();let hitbox = Hitbox {id,@@ -6295,7 +6276,7 @@ impl Window {pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {self.pending_input_observers.clone()- .retain(&(), |callback| callback(self, cx));+ .retain(|callback| callback(self, cx));}fn defer_pending_input_changed(&self, cx: &mut App) {@@ -6663,7 +6644,7 @@ impl Window {f: impl Fn(&mut Window, &mut App) + 'static,) -> Subscription {let window_handle = self.handle;- let (subscription, activate) = cx.global_observers.insert(+ let (subscription, activate) = cx.global_observers.insert_pending(TypeId::of::<G>(),Box::new(move |cx| {window_handle@@ -7233,7 +7214,7 @@ impl Window {}#[cfg(any(feature = "inspector", debug_assertions))]- fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {+ fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {if let Some(mut inspector_element) = inspector_element {inspector_element.paint(self, cx);};diff --git a/crates/settings/src/keymap_file.rs b/crates/settings/src/keymap_file.rsindex 79d2c26a4f5..285b642f159 100644--- a/crates/settings/src/keymap_file.rs+++ b/crates/settings/src/keymap_file.rs@@ -1493,7 +1493,7 @@ impl ActionSequence {Ok((action, _)) => Ok(action),Err(err) => {return Err(ActionBuildError::BuildError {- name: Self::name_for_type().to_string(),+ name: Self::name_for_type().into(),error: anyhow::anyhow!("error at sequence index {index}: {err}"),@@ -1510,7 +1510,7 @@ impl ActionSequence {fn expected_array_error() -> ActionBuildError {ActionBuildError::BuildError {- name: Self::name_for_type().to_string(),+ name: Self::name_for_type().into(),error: anyhow::anyhow!("expected array of actions"),}}