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