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