Skip to main content

gpui/
gpui.rs

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