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#[macro_use]
9mod action;
10mod app;
11
12mod arena;
13mod asset_cache;
14mod assets;
15// Zed's benchmark support is omitted from the gpui-unofficial capture. Keep the
16// pinned source in this package so its public benchmark APIs work in archives.
17#[cfg(feature = "bench-support")]
18#[doc(hidden)]
19pub mod bench_metrics;
20mod bounds_tree;
21mod color;
22/// The default colors used by GPUI.
23pub mod colors;
24#[cfg(feature = "profiler")]
25mod debug_overlay;
26mod element;
27mod elements;
28mod executor;
29mod platform_scheduler;
30pub(crate) use platform_scheduler::PlatformScheduler;
31mod geometry;
32mod gestures;
33mod global;
34#[cfg(gpui_hot_reload)]
35mod hot_reload;
36mod image_texture;
37mod input;
38mod inspector;
39mod interactive;
40mod key_dispatch;
41mod keymap;
42mod path_builder;
43mod platform;
44pub mod prelude;
45/// Profiling utilities for task, frame, and thread performance tracking.
46pub mod profiler;
47#[cfg(any(
48    test,
49    target_os = "windows",
50    target_os = "linux",
51    target_family = "wasm",
52    feature = "test-support",
53    feature = "bench-support"
54))]
55#[expect(missing_docs)]
56pub mod queue;
57/// A seeded, mutable element tree for benchmarks and tests of GPUI rendering.
58#[cfg(any(test, feature = "bench-support"))]
59pub mod randomized_element_tree;
60mod scene;
61#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
62mod seeds;
63mod shared_uri;
64mod spring;
65mod style;
66mod styled;
67mod subscription;
68mod svg_renderer;
69mod tab_stop;
70mod taffy;
71#[cfg(any(test, feature = "test-support"))]
72pub mod test;
73mod text_system;
74mod util;
75mod view;
76mod window;
77
78#[cfg(any(test, feature = "test-support"))]
79pub use proptest;
80#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
81pub use seeds::calculate_seeds;
82
83#[cfg(doc)]
84pub mod _accessibility;
85#[cfg(doc)]
86pub mod _ownership_and_data_flow;
87
88/// Do not touch, here be dragons for use by gpui_macros and such.
89#[doc(hidden)]
90pub mod private {
91    pub use anyhow;
92    pub use inventory;
93    pub use rand;
94    pub use schemars;
95    pub use serde;
96    pub use serde_json;
97}
98
99mod seal {
100    /// A mechanism for restricting implementations of a trait to only those in GPUI.
101    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
102    pub trait Sealed {}
103}
104
105pub use accesskit;
106pub use accesskit::Action as AccessibleAction;
107pub use accesskit::{Orientation, Role, Toggled};
108pub use action::*;
109pub use anyhow::Result;
110pub use app::*;
111pub(crate) use arena::*;
112pub use asset_cache::*;
113pub use assets::*;
114pub use color::*;
115pub use ctor::ctor;
116#[cfg(feature = "profiler")]
117pub use debug_overlay::*;
118pub use element::*;
119pub use elements::*;
120pub use executor::*;
121pub use geometry::*;
122pub use gestures::*;
123pub use global::*;
124pub use gpui_macros::{
125    AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
126};
127pub use spring::*;
128
129/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].
130///
131/// This mirrors `criterion::criterion_group!`, but the group measures with the
132/// `gpui::BenchMeasurement` configured by `BENCH_MEASUREMENT` (see
133/// `BenchMeasurement::from_env`). By default Criterion analyzes wall time
134/// while retired instructions, cycles, IPC, context switches, and the other
135/// counters this machine supports are printed per iteration in the GPUI bench
136/// report. `BENCH_MEASUREMENT=instructions` makes Criterion analyze
137/// process-wide instructions instead, `foreground-instructions` the benchmark
138/// thread's alone, and `wall-time` disables all counters. A
139/// `config = ...` expression may set any other Criterion option; its
140/// measurement is replaced. To measure with something else, call
141/// `criterion::criterion_group!` directly with
142/// `config = criterion::Criterion::default().with_measurement(gpui::BenchMeasurement::new(...))`.
143///
144/// [`gpui::bench`]: crate::bench
145#[macro_export]
146macro_rules! bench_group {
147    (name = $name:ident; config = $config:expr; targets = $($target:path),+ $(,)?) => {
148        criterion::criterion_group! {
149            name = $name;
150            config = ($config).with_measurement($crate::BenchMeasurement::from_env_or_exit());
151            targets = $($target),+
152        }
153    };
154    ($name:ident, $($target:path),+ $(,)?) => {
155        $crate::bench_group! {
156            name = $name;
157            config = criterion::Criterion::default();
158            targets = $($target),+
159        }
160    };
161}
162
163/// Defines the entry point for GPUI Criterion benchmark groups.
164///
165/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the
166/// same shape as ordinary Criterion benchmarks. It also installs
167/// [`CountingAllocator`] as the binary's global allocator, so reports include
168/// heap allocations per iteration. It wraps the system allocator by default;
169/// `allocator = Path;` wraps another unit-struct allocator instead, e.g. to
170/// compare allocators, which pay the same small counting cost:
171///
172/// ```ignore
173/// gpui::bench_main!(allocator = mimalloc::MiMalloc; benches);
174/// ```
175///
176/// `allocator = none;` installs no global allocator, leaving Rust's default and
177/// dropping the allocation metrics from reports.
178#[macro_export]
179macro_rules! bench_main {
180    (allocator = none; $($groups:tt)*) => {
181        criterion::criterion_main!($($groups)*);
182    };
183    (allocator = $allocator:path; $($groups:tt)*) => {
184        #[global_allocator]
185        static GPUI_BENCH_ALLOCATOR: $crate::CountingAllocator<$allocator> =
186            $crate::CountingAllocator::new($allocator);
187
188        criterion::criterion_main!($($groups)*);
189    };
190    ($($groups:tt)*) => {
191        $crate::bench_main!(allocator = ::std::alloc::System; $($groups)*);
192    };
193}
194pub use gpui_shared_string::*;
195pub use gpui_util::arc_cow::ArcCow;
196pub use http_client;
197pub use image_texture::*;
198pub use input::*;
199pub use inspector::*;
200pub use interactive::*;
201use key_dispatch::*;
202pub use keymap::*;
203pub use path_builder::*;
204pub use platform::*;
205pub use profiler::*;
206#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
207pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
208pub use refineable::*;
209pub use scene::*;
210pub use shared_uri::*;
211use std::{any::Any, future::Future};
212pub use style::*;
213pub use styled::*;
214pub use subscription::*;
215/// Subsecond entry points for hot-patching callbacks outside GPUI's render boundaries.
216#[cfg(all(
217    feature = "hot-reload",
218    any(
219        target_os = "macos",
220        target_os = "linux",
221        target_os = "windows",
222        target_os = "ios"
223    )
224))]
225pub use subsecond;
226pub use svg_renderer::*;
227pub(crate) use tab_stop::*;
228use taffy::TaffyLayoutEngine;
229pub use taffy::{AvailableSpace, LayoutId};
230#[cfg(any(test, feature = "test-support"))]
231pub use test::*;
232pub use text_system::*;
233pub use util::{FutureExt, Timeout};
234pub use view::*;
235pub use window::*;
236
237#[cfg(not(target_family = "wasm"))]
238pub use pollster::block_on;
239
240/// The context trait, allows the different contexts in GPUI to be used
241/// interchangeably for certain operations.
242pub trait AppContext {
243    /// Create a new entity in the app context.
244    #[expect(
245        clippy::wrong_self_convention,
246        reason = "`App::new` is an ubiquitous function for creating entities"
247    )]
248    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
249
250    /// Reserve a slot for a entity to be inserted later.
251    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
252    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
253
254    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
255    ///
256    /// [`reserve_entity`]: Self::reserve_entity
257    fn insert_entity<T: 'static>(
258        &mut self,
259        reservation: Reservation<T>,
260        build_entity: impl FnOnce(&mut Context<T>) -> T,
261    ) -> Entity<T>;
262
263    /// Update a entity in the app context.
264    fn update_entity<T, R>(
265        &mut self,
266        handle: &Entity<T>,
267        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
268    ) -> R
269    where
270        T: 'static;
271
272    /// Update a entity in the app context.
273    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
274    where
275        T: 'static;
276
277    /// Read a entity from the app context.
278    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
279    where
280        T: 'static;
281
282    /// Update a window for the given handle.
283    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
284    where
285        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
286
287    /// Run `f` against the entity's *current* window — the most recently
288    /// rendered window that referenced the entity. Returns `None` if the
289    /// entity has no current window or that window is unavailable. See
290    /// [`App::with_window`] for the underlying lookup.
291    fn with_window<R>(
292        &mut self,
293        entity_id: EntityId,
294        f: impl FnOnce(&mut Window, &mut App) -> R,
295    ) -> Option<R>;
296
297    /// Read a window off of the application context.
298    fn read_window<T, R>(
299        &self,
300        window: &WindowHandle<T>,
301        read: impl FnOnce(Entity<T>, &App) -> R,
302    ) -> Result<R>
303    where
304        T: 'static;
305
306    /// Spawn a future on a background thread
307    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
308    where
309        R: Send + 'static;
310
311    /// Read a global from this app context
312    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
313    where
314        G: Global;
315}
316
317/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
318/// Allows you to obtain the [EntityId] for a entity before it is created.
319pub struct Reservation<T>(pub(crate) Slot<T>);
320
321impl<T: 'static> Reservation<T> {
322    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
323    pub fn entity_id(&self) -> EntityId {
324        self.0.entity_id()
325    }
326}
327
328/// This trait is used for the different visual contexts in GPUI that
329/// require a window to be present.
330pub trait VisualContext: AppContext {
331    /// The result type for window operations.
332    type Result<T>;
333
334    /// Returns the handle of the window associated with this context.
335    fn window_handle(&self) -> AnyWindowHandle;
336
337    /// Update a view with the given callback
338    fn update_window_entity<T: 'static, R>(
339        &mut self,
340        entity: &Entity<T>,
341        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
342    ) -> Self::Result<R>;
343
344    /// Create a new entity, with access to `Window`.
345    fn new_window_entity<T: 'static>(
346        &mut self,
347        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
348    ) -> Self::Result<Entity<T>>;
349
350    /// Replace the root view of a window with a new view.
351    fn replace_root_view<V>(
352        &mut self,
353        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
354    ) -> Self::Result<Entity<V>>
355    where
356        V: 'static + Render;
357
358    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
359    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
360    where
361        V: Focusable;
362}
363
364/// A trait for tying together the types of a GPUI entity and the events it can
365/// emit.
366pub trait EventEmitter<E: Any>: 'static {}
367
368/// A helper trait for auto-implementing certain methods on contexts that
369/// can be used interchangeably.
370pub trait BorrowAppContext {
371    /// Set a global value on the context.
372    fn set_global<T: Global>(&mut self, global: T);
373    /// Updates the global state of the given type.
374    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
375    where
376        G: Global;
377    /// Updates the global state of the given type, creating a default if it didn't exist before.
378    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
379    where
380        G: Global + Default;
381}
382
383impl<C> BorrowAppContext for C
384where
385    C: std::borrow::BorrowMut<App>,
386{
387    fn set_global<G: Global>(&mut self, global: G) {
388        self.borrow_mut().set_global(global)
389    }
390
391    #[track_caller]
392    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
393    where
394        G: Global,
395    {
396        let mut global = self.borrow_mut().lease_global::<G>();
397        let result = f(&mut global, self);
398        self.borrow_mut().end_global_lease(global);
399        result
400    }
401
402    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
403    where
404        G: Global + Default,
405    {
406        self.borrow_mut().default_global::<G>();
407        self.update_global(f)
408    }
409}
410
411/// Information about the GPU GPUI is running on.
412#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
413pub struct GpuSpecs {
414    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
415    pub is_software_emulated: bool,
416    /// The name of the device, as reported by Vulkan.
417    pub device_name: String,
418    /// The name of the driver, as reported by Vulkan.
419    pub driver_name: String,
420    /// Further information about the driver, as reported by Vulkan.
421    pub driver_info: String,
422}
423
424mod backdrop;
425mod backdrop_cache;
426pub use backdrop::*;
427pub use backdrop_cache::*;
428
429mod layer_effect;
430pub use layer_effect::*;