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    #[track_caller]
221    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
222    where
223        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
224
225    /// Run `f` against the entity's *current* window — the most recently
226    /// rendered window that referenced the entity. Returns `None` if the
227    /// entity has no current window or that window is unavailable. See
228    /// [`App::with_window`] for the underlying lookup.
229    fn with_window<R>(
230        &mut self,
231        entity_id: EntityId,
232        f: impl FnOnce(&mut Window, &mut App) -> R,
233    ) -> Option<R>;
234
235    /// Read a window off of the application context.
236    fn read_window<T, R>(
237        &self,
238        window: &WindowHandle<T>,
239        read: impl FnOnce(Entity<T>, &App) -> R,
240    ) -> Result<R>
241    where
242        T: 'static;
243
244    /// Spawn a future on a background thread
245    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
246    where
247        R: Send + 'static;
248
249    /// Read a global from this app context
250    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
251    where
252        G: Global;
253}
254
255/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
256/// Allows you to obtain the [EntityId] for a entity before it is created.
257pub struct Reservation<T>(pub(crate) Slot<T>);
258
259impl<T: 'static> Reservation<T> {
260    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
261    pub fn entity_id(&self) -> EntityId {
262        self.0.entity_id()
263    }
264}
265
266/// This trait is used for the different visual contexts in GPUI that
267/// require a window to be present.
268pub trait VisualContext: AppContext {
269    /// The result type for window operations.
270    type Result<T>;
271
272    /// Returns the handle of the window associated with this context.
273    fn window_handle(&self) -> AnyWindowHandle;
274
275    /// Update a view with the given callback
276    fn update_window_entity<T: 'static, R>(
277        &mut self,
278        entity: &Entity<T>,
279        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
280    ) -> Self::Result<R>;
281
282    /// Create a new entity, with access to `Window`.
283    fn new_window_entity<T: 'static>(
284        &mut self,
285        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
286    ) -> Self::Result<Entity<T>>;
287
288    /// Replace the root view of a window with a new view.
289    fn replace_root_view<V>(
290        &mut self,
291        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
292    ) -> Self::Result<Entity<V>>
293    where
294        V: 'static + Render;
295
296    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
297    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
298    where
299        V: Focusable;
300}
301
302/// A trait for tying together the types of a GPUI entity and the events it can
303/// emit.
304pub trait EventEmitter<E: Any>: 'static {}
305
306/// A helper trait for auto-implementing certain methods on contexts that
307/// can be used interchangeably.
308pub trait BorrowAppContext {
309    /// Set a global value on the context.
310    fn set_global<T: Global>(&mut self, global: T);
311    /// Updates the global state of the given type.
312    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
313    where
314        G: Global;
315    /// Updates the global state of the given type, creating a default if it didn't exist before.
316    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
317    where
318        G: Global + Default;
319}
320
321impl<C> BorrowAppContext for C
322where
323    C: std::borrow::BorrowMut<App>,
324{
325    fn set_global<G: Global>(&mut self, global: G) {
326        self.borrow_mut().set_global(global)
327    }
328
329    #[track_caller]
330    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
331    where
332        G: Global,
333    {
334        let mut global = self.borrow_mut().lease_global::<G>();
335        let result = f(&mut global, self);
336        self.borrow_mut().end_global_lease(global);
337        result
338    }
339
340    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
341    where
342        G: Global + Default,
343    {
344        self.borrow_mut().default_global::<G>();
345        self.update_global(f)
346    }
347}
348
349/// Information about the GPU GPUI is running on.
350#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
351pub struct GpuSpecs {
352    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
353    pub is_software_emulated: bool,
354    /// The name of the device, as reported by Vulkan.
355    pub device_name: String,
356    /// The name of the driver, as reported by Vulkan.
357    pub driver_name: String,
358    /// Further information about the driver, as reported by Vulkan.
359    pub driver_info: String,
360}
361
362mod backdrop;
363mod backdrop_cache;
364pub use backdrop::*;
365pub use backdrop_cache::*;
366
367mod layer_effect;
368pub use layer_effect::*;