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