gpui: Improve `Global` ergonomics (#11923)

Marshall Bowers created

This PR adds some ergonomic improvements when working with GPUI
`Global`s.

Two new traits have been addedโ€”`ReadGlobal` and `UpdateGlobal`โ€”that
provide associated functions on any type that implements `Global` for
accessing and updating the global without needing to call the methods on
the `cx` directly (which generally involves qualifying the type).

I looked into adding `ObserveGlobal` as well, but this seems a bit
trickier to implement as the signatures of `cx.observe_global` vary
slightly between the different contexts.

Release Notes:

- N/A

Change summary

crates/assistant/src/assistant.rs            |  6 +-
crates/assistant/src/assistant_panel.rs      |  8 +-
crates/assistant/src/assistant_settings.rs   |  8 +-
crates/assistant2/src/assistant2.rs          |  6 +-
crates/assistant2/src/completion_provider.rs |  6 -
crates/assistant2/src/ui/composer.rs         |  4 
crates/gpui/src/global.rs                    | 62 ++++++++++++++++++++++
crates/gpui/src/gpui.rs                      | 14 ----
8 files changed, 81 insertions(+), 33 deletions(-)

Detailed changes

crates/assistant/src/assistant.rs ๐Ÿ”—

@@ -12,7 +12,7 @@ use assistant_settings::{AnthropicModel, AssistantSettings, OpenAiModel, ZedDotD
 use client::{proto, Client};
 use command_palette_hooks::CommandPaletteFilter;
 pub(crate) use completion_provider::*;
-use gpui::{actions, AppContext, BorrowAppContext, Global, SharedString};
+use gpui::{actions, AppContext, Global, SharedString, UpdateGlobal};
 pub(crate) use saved_conversation::*;
 use serde::{Deserialize, Serialize};
 use settings::{Settings, SettingsStore};
@@ -233,13 +233,13 @@ pub fn init(client: Arc<Client>, cx: &mut AppContext) {
     CommandPaletteFilter::update_global(cx, |filter, _cx| {
         filter.hide_namespace(Assistant::NAMESPACE);
     });
-    cx.update_global(|assistant: &mut Assistant, cx: &mut AppContext| {
+    Assistant::update_global(cx, |assistant, cx| {
         let settings = AssistantSettings::get_global(cx);
 
         assistant.set_enabled(settings.enabled, cx);
     });
     cx.observe_global::<SettingsStore>(|cx| {
-        cx.update_global(|assistant: &mut Assistant, cx: &mut AppContext| {
+        Assistant::update_global(cx, |assistant, cx| {
             let settings = AssistantSettings::get_global(cx);
 
             assistant.set_enabled(settings.enabled, cx);

crates/assistant/src/assistant_panel.rs ๐Ÿ”—

@@ -28,8 +28,8 @@ use gpui::{
     AsyncWindowContext, AvailableSpace, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
     FocusableView, FontStyle, FontWeight, HighlightStyle, InteractiveElement, IntoElement, Model,
     ModelContext, ParentElement, Pixels, Render, SharedString, StatefulInteractiveElement, Styled,
-    Subscription, Task, TextStyle, UniformListScrollHandle, View, ViewContext, VisualContext,
-    WeakModel, WeakView, WhiteSpace, WindowContext,
+    Subscription, Task, TextStyle, UniformListScrollHandle, UpdateGlobal, View, ViewContext,
+    VisualContext, WeakModel, WeakView, WhiteSpace, WindowContext,
 };
 use language::{language_settings::SoftWrap, Buffer, LanguageRegistry, Point, ToOffset as _};
 use multi_buffer::MultiBufferRow;
@@ -240,7 +240,7 @@ impl AssistantPanel {
             || prev_settings_version != CompletionProvider::global(cx).settings_version()
         {
             self.authentication_prompt =
-                Some(cx.update_global::<CompletionProvider, _>(|provider, cx| {
+                Some(CompletionProvider::update_global(cx, |provider, cx| {
                     provider.authentication_prompt(cx)
                 }));
         }
@@ -1088,7 +1088,7 @@ impl AssistantPanel {
     }
 
     fn authenticate(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
-        cx.update_global::<CompletionProvider, _>(|provider, cx| provider.authenticate(cx))
+        CompletionProvider::update_global(cx, |provider, cx| provider.authenticate(cx))
     }
 
     fn render_signed_in(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {

crates/assistant/src/assistant_settings.rs ๐Ÿ”—

@@ -418,7 +418,7 @@ fn merge<T: Copy>(target: &mut T, value: Option<T>) {
 
 #[cfg(test)]
 mod tests {
-    use gpui::{AppContext, BorrowAppContext};
+    use gpui::{AppContext, UpdateGlobal};
     use settings::SettingsStore;
 
     use super::*;
@@ -440,7 +440,7 @@ mod tests {
         );
 
         // Ensure backward-compatibility.
-        cx.update_global::<SettingsStore, _>(|store, cx| {
+        SettingsStore::update_global(cx, |store, cx| {
             store
                 .set_user_settings(
                     r#"{
@@ -460,7 +460,7 @@ mod tests {
                 low_speed_timeout_in_seconds: None,
             }
         );
-        cx.update_global::<SettingsStore, _>(|store, cx| {
+        SettingsStore::update_global(cx, |store, cx| {
             store
                 .set_user_settings(
                     r#"{
@@ -482,7 +482,7 @@ mod tests {
         );
 
         // The new version supports setting a custom model when using zed.dev.
-        cx.update_global::<SettingsStore, _>(|store, cx| {
+        SettingsStore::update_global(cx, |store, cx| {
             store
                 .set_user_settings(
                     r#"{

crates/assistant2/src/assistant2.rs ๐Ÿ”—

@@ -24,7 +24,7 @@ use fs::Fs;
 use futures::{future::join_all, StreamExt};
 use gpui::{
     list, AnyElement, AppContext, AsyncWindowContext, ClickEvent, EventEmitter, FocusHandle,
-    FocusableView, ListAlignment, ListState, Model, Render, Task, View, WeakView,
+    FocusableView, ListAlignment, ListState, Model, ReadGlobal, Render, Task, View, WeakView,
 };
 use language::{language_settings::SoftWrap, LanguageRegistry};
 use markdown::{Markdown, MarkdownStyle};
@@ -288,7 +288,7 @@ impl AssistantChat {
         workspace: WeakView<Workspace>,
         cx: &mut ViewContext<Self>,
     ) -> Self {
-        let model = CompletionProvider::get(cx).default_model();
+        let model = CompletionProvider::global(cx).default_model();
         let view = cx.view().downgrade();
         let list_state = ListState::new(
             0,
@@ -550,7 +550,7 @@ impl AssistantChat {
                 let messages = messages.await?;
 
                 let completion = cx.update(|cx| {
-                    CompletionProvider::get(cx).complete(
+                    CompletionProvider::global(cx).complete(
                         model_name,
                         messages,
                         Vec::new(),

crates/assistant2/src/completion_provider.rs ๐Ÿ”—

@@ -2,7 +2,7 @@ use anyhow::Result;
 use assistant_tooling::ToolFunctionDefinition;
 use client::{proto, Client};
 use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
-use gpui::{AppContext, Global};
+use gpui::Global;
 use std::sync::Arc;
 
 pub use open_ai::RequestMessage as CompletionMessage;
@@ -11,10 +11,6 @@ pub use open_ai::RequestMessage as CompletionMessage;
 pub struct CompletionProvider(Arc<dyn CompletionProviderBackend>);
 
 impl CompletionProvider {
-    pub fn get(cx: &AppContext) -> &Self {
-        cx.global::<CompletionProvider>()
-    }
-
     pub fn new(backend: impl CompletionProviderBackend) -> Self {
         Self(Arc::new(backend))
     }

crates/assistant2/src/ui/composer.rs ๐Ÿ”—

@@ -3,7 +3,7 @@ use crate::{
     AssistantChat, CompletionProvider,
 };
 use editor::{Editor, EditorElement, EditorStyle};
-use gpui::{AnyElement, FontStyle, FontWeight, TextStyle, View, WeakView, WhiteSpace};
+use gpui::{AnyElement, FontStyle, FontWeight, ReadGlobal, TextStyle, View, WeakView, WhiteSpace};
 use settings::Settings;
 use theme::ThemeSettings;
 use ui::{popover_menu, prelude::*, ButtonLike, ContextMenu, Divider, TextSize, Tooltip};
@@ -139,7 +139,7 @@ impl RenderOnce for ModelSelector {
         popover_menu("model-switcher")
             .menu(move |cx| {
                 ContextMenu::build(cx, |mut menu, cx| {
-                    for model in CompletionProvider::get(cx).available_models() {
+                    for model in CompletionProvider::global(cx).available_models() {
                         menu = menu.custom_entry(
                             {
                                 let model = model.clone();

crates/gpui/src/global.rs ๐Ÿ”—

@@ -0,0 +1,62 @@
+use crate::{AppContext, BorrowAppContext};
+
+/// A marker trait for types that can be stored in GPUI's global state.
+///
+/// This trait exists to provide type-safe access to globals by ensuring only
+/// types that implement [`Global`] can be used with the accessor methods. For
+/// example, trying to access a global with a type that does not implement
+/// [`Global`] will result in a compile-time error.
+///
+/// Implement this on types you want to store in the context as a global.
+///
+/// ## Restricting Access to Globals
+///
+/// In some situations you may need to store some global state, but want to
+/// restrict access to reading it or writing to it.
+///
+/// In these cases, Rust's visibility system can be used to restrict access to
+/// a global value. For example, you can create a private struct that implements
+/// [`Global`] and holds the global state. Then create a newtype struct that wraps
+/// the global type and create custom accessor methods to expose the desired subset
+/// of operations.
+pub trait Global: 'static {
+    // This trait is intentionally left empty, by virtue of being a marker trait.
+    //
+    // Use additional traits with blanket implementations to attach functionality
+    // to types that implement `Global`.
+}
+
+/// A trait for reading a global value from the context.
+pub trait ReadGlobal {
+    /// Returns the global instance of the implementing type.
+    ///
+    /// Panics if a global for that type has not been assigned.
+    fn global(cx: &AppContext) -> &Self;
+}
+
+impl<T: Global> ReadGlobal for T {
+    fn global(cx: &AppContext) -> &Self {
+        cx.global::<T>()
+    }
+}
+
+/// A trait for updating a global value in the context.
+pub trait UpdateGlobal {
+    /// Updates the global instance of the implementing type using the provided closure.
+    ///
+    /// This method provides the closure with mutable access to the context and the global simultaneously.
+    fn update_global<C, F, R>(cx: &mut C, update: F) -> R
+    where
+        C: BorrowAppContext,
+        F: FnOnce(&mut Self, &mut C) -> R;
+}
+
+impl<T: Global> UpdateGlobal for T {
+    fn update_global<C, F, R>(cx: &mut C, update: F) -> R
+    where
+        C: BorrowAppContext,
+        F: FnOnce(&mut Self, &mut C) -> R,
+    {
+        cx.update_global(update)
+    }
+}

crates/gpui/src/gpui.rs ๐Ÿ”—

@@ -77,6 +77,7 @@ mod element;
 mod elements;
 mod executor;
 mod geometry;
+mod global;
 mod input;
 mod interactive;
 mod key_dispatch;
@@ -125,6 +126,7 @@ pub use element::*;
 pub use elements::*;
 pub use executor::*;
 pub use geometry::*;
+pub use global::*;
 pub use gpui_macros::{register_action, test, IntoElement, Render};
 pub use input::*;
 pub use interactive::*;
@@ -327,15 +329,3 @@ impl<T> Flatten<T> for Result<T> {
         self
     }
 }
-
-/// A marker trait for types that can be stored in GPUI's global state.
-///
-/// This trait exists to provide type-safe access to globals by restricting
-/// the scope from which they can be accessed. For instance, the actual type
-/// that implements [`Global`] can be private, with public accessor functions
-/// that enforce correct usage.
-///
-/// Implement this on types you want to store in the context as a global.
-pub trait Global: 'static {
-    // This trait is intentionally left empty, by virtue of being a marker trait.
-}