gpui: Improve Global ergonomics (#11923)

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
This commit is contained in:
Marshall Bowers 2024-05-16 12:47:43 -04:00 committed by GitHub
parent 1b261608c6
commit c1e291bc96
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 81 additions and 33 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ use crate::{
AssistantChat, CompletionProvider, AssistantChat, CompletionProvider,
}; };
use editor::{Editor, EditorElement, EditorStyle}; 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 settings::Settings;
use theme::ThemeSettings; use theme::ThemeSettings;
use ui::{popover_menu, prelude::*, ButtonLike, ContextMenu, Divider, TextSize, Tooltip}; use ui::{popover_menu, prelude::*, ButtonLike, ContextMenu, Divider, TextSize, Tooltip};
@ -139,7 +139,7 @@ impl RenderOnce for ModelSelector {
popover_menu("model-switcher") popover_menu("model-switcher")
.menu(move |cx| { .menu(move |cx| {
ContextMenu::build(cx, |mut menu, 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( menu = menu.custom_entry(
{ {
let model = model.clone(); let model = model.clone();

62
crates/gpui/src/global.rs Normal file
View File

@ -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)
}
}

View File

@ -77,6 +77,7 @@ mod element;
mod elements; mod elements;
mod executor; mod executor;
mod geometry; mod geometry;
mod global;
mod input; mod input;
mod interactive; mod interactive;
mod key_dispatch; mod key_dispatch;
@ -125,6 +126,7 @@ pub use element::*;
pub use elements::*; pub use elements::*;
pub use executor::*; pub use executor::*;
pub use geometry::*; pub use geometry::*;
pub use global::*;
pub use gpui_macros::{register_action, test, IntoElement, Render}; pub use gpui_macros::{register_action, test, IntoElement, Render};
pub use input::*; pub use input::*;
pub use interactive::*; pub use interactive::*;
@ -327,15 +329,3 @@ impl<T> Flatten<T> for Result<T> {
self 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.
}