Skip to main content

gpui/
gpui.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
4
5pub extern crate accesskit;
6pub extern crate http_client;
7#[cfg(any(test, feature = "test-support"))]
8pub extern crate proptest;
9/// Subsecond entry points for hot-patching callbacks outside GPUI's render boundaries.
10#[cfg(all(
11    feature = "hot-reload",
12    any(
13        target_os = "macos",
14        target_os = "linux",
15        target_os = "windows",
16        target_os = "ios"
17    )
18))]
19pub extern crate subsecond;
20
21extern crate self as gpui;
22
23pub mod colors;
24pub mod prelude;
25pub mod profiler;
26
27#[macro_use]
28mod action;
29mod app;
30mod arena;
31mod asset_cache;
32mod assets;
33// Zed's benchmark support is omitted from the gpui-unofficial capture. Keep the
34// pinned source in this package so its public benchmark APIs work in archives.
35#[cfg(feature = "bench-support")]
36#[doc(hidden)]
37pub mod bench_metrics;
38mod bounds_tree;
39mod color;
40mod element;
41mod elements;
42mod executor;
43mod geometry;
44mod gestures;
45mod global;
46mod image_texture;
47mod input;
48mod inspector;
49mod interactive;
50mod key_dispatch;
51mod keymap;
52mod path_builder;
53mod platform;
54mod platform_scheduler;
55mod scene;
56mod shared_uri;
57mod spring;
58mod style;
59mod styled;
60mod subscription;
61mod svg_renderer;
62mod tab_stop;
63mod taffy;
64mod text_system;
65mod util;
66mod view;
67mod window;
68
69#[cfg(feature = "profiler")]
70mod debug_overlay;
71#[cfg(feature = "profiler")]
72pub use debug_overlay::*;
73
74#[cfg(gpui_hot_reload)]
75mod hot_reload;
76#[cfg(any(
77    test,
78    target_os = "windows",
79    target_os = "linux",
80    target_family = "wasm",
81    feature = "test-support",
82    feature = "bench-support"
83))]
84pub mod queue;
85
86#[cfg(any(test, feature = "bench-support"))]
87pub mod randomized_element_tree;
88
89mod bench;
90#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
91mod seeds;
92#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
93pub use seeds::calculate_seeds;
94
95#[cfg(any(test, feature = "test-support"))]
96pub mod test;
97#[cfg(any(test, feature = "test-support"))]
98pub use test::*;
99
100#[cfg(doc)]
101pub mod _accessibility;
102#[cfg(doc)]
103pub mod _ownership_and_data_flow;
104
105/// Do not touch, here be dragons for use by gpui_macros and such.
106#[doc(hidden)]
107pub mod private {
108    pub use anyhow;
109    pub use inventory;
110    pub use rand;
111    pub use schemars;
112    pub use serde;
113    pub use serde_json;
114}
115
116#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
117pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
118
119pub use accesskit::{Action as AccessibleAction, Orientation, Role, Toggled};
120pub use action::*;
121pub use anyhow::Result;
122pub use app::*;
123pub use asset_cache::*;
124pub use assets::*;
125pub use color::*;
126pub use ctor::ctor;
127pub use element::*;
128pub use elements::*;
129pub use executor::*;
130pub use geometry::*;
131pub use gestures::*;
132pub use global::*;
133pub use gpui_macros::{
134    AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
135};
136pub use gpui_shared_string::*;
137pub use gpui_util::arc_cow::ArcCow;
138pub use image_texture::*;
139pub use input::*;
140pub use inspector::*;
141pub use interactive::*;
142pub use keymap::*;
143pub use path_builder::*;
144pub use platform::*;
145pub use profiler::*;
146pub use refineable::*;
147pub use scene::*;
148pub use shared_uri::*;
149pub use spring::*;
150pub use style::*;
151pub use styled::*;
152pub use subscription::*;
153pub use svg_renderer::*;
154pub use taffy::{AvailableSpace, LayoutId};
155pub use text_system::*;
156pub use util::{FutureExt, Timeout};
157pub use view::*;
158pub use window::*;
159
160#[cfg(not(target_family = "wasm"))]
161pub use pollster::block_on;
162
163pub(crate) use arena::*;
164pub(crate) use platform_scheduler::PlatformScheduler;
165pub(crate) use tab_stop::*;
166
167use std::{any::Any, future::Future};
168
169use key_dispatch::*;
170
171mod seal {
172    /// A mechanism for restricting implementations of a trait to only those in GPUI.
173    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
174    pub trait Sealed {}
175}
176
177/// The context trait, allows the different contexts in GPUI to be used
178/// interchangeably for certain operations.
179pub trait AppContext {
180    /// Create a new entity in the app context.
181    #[expect(
182        clippy::wrong_self_convention,
183        reason = "`App::new` is an ubiquitous function for creating entities"
184    )]
185    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
186
187    /// Reserve a slot for a entity to be inserted later.
188    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
189    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
190
191    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
192    ///
193    /// [`reserve_entity`]: Self::reserve_entity
194    fn insert_entity<T: 'static>(
195        &mut self,
196        reservation: Reservation<T>,
197        build_entity: impl FnOnce(&mut Context<T>) -> T,
198    ) -> Entity<T>;
199
200    /// Update a entity in the app context.
201    fn update_entity<T, R>(
202        &mut self,
203        handle: &Entity<T>,
204        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
205    ) -> R
206    where
207        T: 'static;
208
209    /// Update a entity in the app context.
210    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
211    where
212        T: 'static;
213
214    /// Read a entity from the app context.
215    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
216    where
217        T: 'static;
218
219    /// Update a window for the given handle.
220    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
221    where
222        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
223
224    /// Run `f` against the entity's *current* window — the most recently
225    /// rendered window that referenced the entity. Returns `None` if the
226    /// entity has no current window or that window is unavailable. See
227    /// [`App::with_window`] for the underlying lookup.
228    fn with_window<R>(
229        &mut self,
230        entity_id: EntityId,
231        f: impl FnOnce(&mut Window, &mut App) -> R,
232    ) -> Option<R>;
233
234    /// Read a window off of the application context.
235    fn read_window<T, R>(
236        &self,
237        window: &WindowHandle<T>,
238        read: impl FnOnce(Entity<T>, &App) -> R,
239    ) -> Result<R>
240    where
241        T: 'static;
242
243    /// Spawn a future on a background thread
244    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
245    where
246        R: Send + 'static;
247
248    /// Read a global from this app context
249    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
250    where
251        G: Global;
252}
253
254/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
255/// Allows you to obtain the [EntityId] for a entity before it is created.
256pub struct Reservation<T>(pub(crate) Slot<T>);
257
258impl<T: 'static> Reservation<T> {
259    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
260    pub fn entity_id(&self) -> EntityId {
261        self.0.entity_id()
262    }
263}
264
265/// This trait is used for the different visual contexts in GPUI that
266/// require a window to be present.
267pub trait VisualContext: AppContext {
268    /// The result type for window operations.
269    type Result<T>;
270
271    /// Returns the handle of the window associated with this context.
272    fn window_handle(&self) -> AnyWindowHandle;
273
274    /// Update a view with the given callback
275    fn update_window_entity<T: 'static, R>(
276        &mut self,
277        entity: &Entity<T>,
278        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
279    ) -> Self::Result<R>;
280
281    /// Create a new entity, with access to `Window`.
282    fn new_window_entity<T: 'static>(
283        &mut self,
284        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
285    ) -> Self::Result<Entity<T>>;
286
287    /// Replace the root view of a window with a new view.
288    fn replace_root_view<V>(
289        &mut self,
290        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
291    ) -> Self::Result<Entity<V>>
292    where
293        V: 'static + Render;
294
295    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
296    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
297    where
298        V: Focusable;
299}
300
301/// A trait for tying together the types of a GPUI entity and the events it can
302/// emit.
303pub trait EventEmitter<E: Any>: 'static {}
304
305/// A helper trait for auto-implementing certain methods on contexts that
306/// can be used interchangeably.
307pub trait BorrowAppContext {
308    /// Set a global value on the context.
309    fn set_global<T: Global>(&mut self, global: T);
310    /// Updates the global state of the given type.
311    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
312    where
313        G: Global;
314    /// Updates the global state of the given type, creating a default if it didn't exist before.
315    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
316    where
317        G: Global + Default;
318}
319
320impl<C> BorrowAppContext for C
321where
322    C: std::borrow::BorrowMut<App>,
323{
324    fn set_global<G: Global>(&mut self, global: G) {
325        self.borrow_mut().set_global(global)
326    }
327
328    #[track_caller]
329    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
330    where
331        G: Global,
332    {
333        let mut global = self.borrow_mut().lease_global::<G>();
334        let result = f(&mut global, self);
335        self.borrow_mut().end_global_lease(global);
336        result
337    }
338
339    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
340    where
341        G: Global + Default,
342    {
343        self.borrow_mut().default_global::<G>();
344        self.update_global(f)
345    }
346}
347
348/// Information about the GPU GPUI is running on.
349#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
350pub struct GpuSpecs {
351    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
352    pub is_software_emulated: bool,
353    /// The name of the device, as reported by Vulkan.
354    pub device_name: String,
355    /// The name of the driver, as reported by Vulkan.
356    pub driver_name: String,
357    /// Further information about the driver, as reported by Vulkan.
358    pub driver_info: String,
359}
360
361mod backdrop;
362mod backdrop_cache;
363pub use backdrop::*;
364pub use backdrop_cache::*;
365
366mod layer_effect;
367pub use layer_effect::*;