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