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;
21mod element;
22mod elements;
23mod executor;
24mod platform_scheduler;
25pub(crate) use platform_scheduler::PlatformScheduler;
26mod geometry;
27mod gestures;
28mod global;
29mod input;
30mod inspector;
31mod interactive;
32mod key_dispatch;
33mod keymap;
34mod lerp;
35mod path_builder;
36mod platform;
37pub mod prelude;
38/// Profiling utilities for task, frame, and thread performance tracking.
39pub mod profiler;
40#[cfg(any(
41    test,
42    target_os = "windows",
43    target_os = "linux",
44    target_family = "wasm",
45    feature = "bench"
46))]
47#[expect(missing_docs)]
48pub mod queue;
49mod scene;
50mod shared_uri;
51mod style;
52mod styled;
53mod subscription;
54mod svg_renderer;
55mod tab_stop;
56mod taffy;
57#[cfg(any(test, feature = "test-support"))]
58pub mod test;
59mod text_system;
60mod transition;
61mod util;
62mod view;
63mod window;
64
65#[cfg(any(test, feature = "test-support"))]
66pub use proptest;
67
68#[cfg(doc)]
69pub mod _accessibility;
70#[cfg(doc)]
71pub mod _ownership_and_data_flow;
72
73/// Do not touch, here be dragons for use by gpui_macros and such.
74#[doc(hidden)]
75pub mod private {
76    pub use anyhow;
77    pub use inventory;
78    pub use schemars;
79    pub use serde;
80    pub use serde_json;
81}
82
83mod seal {
84    /// A mechanism for restricting implementations of a trait to only those in GPUI.
85    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
86    pub trait Sealed {}
87}
88
89pub use accesskit;
90pub use accesskit::Action as AccessibleAction;
91pub use accesskit::{Orientation, Role, Toggled};
92pub use action::*;
93pub use anyhow::Result;
94pub use app::*;
95pub(crate) use arena::*;
96pub use asset_cache::*;
97pub use assets::*;
98pub use color::*;
99pub use ctor::ctor;
100pub use element::*;
101pub use elements::*;
102pub use executor::*;
103pub use geometry::*;
104pub use gestures::*;
105pub use global::*;
106pub use gpui_macros::{
107    AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
108};
109
110/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].
111///
112/// This mirrors `criterion::criterion_group!` so GPUI benchmark files can keep the
113/// same shape as ordinary Criterion benchmarks.
114///
115/// [`gpui::bench`]: crate::bench
116#[macro_export]
117macro_rules! bench_group {
118    ($($tokens:tt)*) => {
119        criterion::criterion_group!($($tokens)*);
120    };
121}
122
123/// Defines the entry point for GPUI Criterion benchmark groups.
124///
125/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the
126/// same shape as ordinary Criterion benchmarks.
127#[macro_export]
128macro_rules! bench_main {
129    ($($tokens:tt)*) => {
130        criterion::criterion_main!($($tokens)*);
131    };
132}
133pub use gpui_shared_string::*;
134pub use gpui_util::arc_cow::ArcCow;
135/// HTTP client abstraction for making requests.
136pub mod http_client;
137pub use input::*;
138pub use inspector::*;
139pub use interactive::*;
140use key_dispatch::*;
141pub use keymap::*;
142pub use lerp::*;
143pub use path_builder::*;
144pub use platform::*;
145pub use profiler::*;
146#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
147pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
148pub use refineable::*;
149pub use scene::*;
150pub use shared_uri::*;
151use std::{any::Any, future::Future};
152pub use style::*;
153pub use styled::*;
154pub use subscription::*;
155pub use svg_renderer::*;
156pub(crate) use tab_stop::*;
157use taffy::TaffyLayoutEngine;
158pub use taffy::{AvailableSpace, LayoutId};
159#[cfg(any(test, feature = "test-support"))]
160pub use test::*;
161pub use text_system::*;
162pub use transition::*;
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}