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