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