Skip to main content

gpui_authoring/
gpui_authoring.rs

1//! GPUI's authoring layer: the reactive store, the windows, and the declarative
2//! element DSL that composes them.
3//!
4//! This crate holds [`App`], [`Window`] and the context types, the entities and
5//! views built on them, and the element tree that renders through the engine
6//! contracts in [`gpui_engine`] onto the windowing SPI in [`gpui_platform`].
7//!
8//! The element DSL is not separable from the runtime: an element is laid out and
9//! painted with a concrete [`Window`] and [`App`], so both tiers described in the
10//! [authoring guide](crate::_authoring) live here. What *is* swappable sits
11//! underneath, behind [`LayoutEngine`], [`SceneRenderer`] and [`Platform`], or
12//! rides along in [`Style::custom`]. How a frame itself is built and paced is
13//! swappable too, through the [`FramePipeline`] a window draws with — see the
14//! [frame pipeline guide](crate::_frame_pipeline).
15//!
16//! Above this crate sits `gpui_runtime`, which holds `Application` — how a host
17//! program builds, configures and starts an app — and above that, the `gpui`
18//! crate: a thin facade re-exporting this, the runtime, and the platform
19//! backends, so applications keep importing `gpui`.
20
21#![warn(missing_docs)]
22#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
23#![allow(clippy::collapsible_else_if)] // False positives in platform specific code
24#![allow(unused_mut)] // False positives in platform specific code
25
26// Macros generated by `gpui_macros` name `gpui::` paths, so within this crate
27// `gpui` is an alias for `gpui_authoring`.
28extern crate self as gpui;
29
30#[macro_use]
31mod action;
32mod app;
33
34mod arena;
35mod asset_cache;
36mod assets;
37/// The default colors used by GPUI.
38pub mod colors;
39#[cfg(feature = "profiler")]
40mod debug_overlay;
41mod element;
42mod elements;
43mod engine_layout;
44mod executor;
45mod gestures;
46mod global;
47mod input;
48mod inspector;
49mod interactive;
50mod key_dispatch;
51mod keymap;
52mod path_builder;
53mod platform;
54pub mod prelude;
55/// Profiling utilities for task, frame, and thread performance tracking.
56pub mod profiler;
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;
60#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
61mod seeds;
62mod shared_uri;
63mod spring;
64mod style;
65mod styled;
66mod subscription;
67mod svg_renderer;
68mod tab_stop;
69#[cfg(any(test, feature = "test-support"))]
70pub mod test;
71mod text_system;
72mod util;
73mod view;
74mod window;
75
76#[cfg(any(test, feature = "test-support"))]
77pub use proptest;
78#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
79pub use seeds::calculate_seeds;
80
81/// Accessibility guide: exposing UI state to assistive technology.
82pub mod _accessibility;
83/// Authoring guide: the two public tiers of the UI API.
84pub mod _authoring;
85/// Frame pipeline guide: how to write and install one.
86pub mod _frame_pipeline;
87/// How GPUI's ownership and data-flow model works.
88pub mod _ownership_and_data_flow;
89
90/// Do not touch, here be dragons for use by gpui_macros and such.
91#[doc(hidden)]
92pub mod private {
93    pub use anyhow;
94    pub use inventory;
95    pub use rand;
96    pub use schemars;
97    pub use serde;
98    pub use serde_json;
99}
100
101mod seal {
102    /// A mechanism for restricting implementations of a trait to only those in GPUI.
103    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
104    pub trait Sealed {}
105}
106
107pub use accesskit;
108pub use accesskit::Action as AccessibleAction;
109pub use accesskit::{Orientation, Role, Toggled};
110pub use action::*;
111pub use anyhow::Result;
112pub use app::*;
113pub(crate) use arena::*;
114pub use asset_cache::*;
115pub use assets::*;
116pub use ctor::ctor;
117#[cfg(feature = "profiler")]
118pub use debug_overlay::*;
119pub use element::*;
120pub use elements::*;
121pub use executor::*;
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_engine::*;
195pub use gpui_engine_default::*;
196pub use gpui_platform::*;
197pub use gpui_util::arc_cow::ArcCow;
198pub use http_client;
199pub use input::*;
200pub use inspector::*;
201pub use interactive::*;
202use key_dispatch::*;
203pub use keymap::*;
204pub use path_builder::*;
205pub use platform::*;
206pub use profiler::*;
207pub use refineable::*;
208pub use shared_uri::*;
209use std::{any::Any, future::Future};
210pub use style::*;
211pub use styled::*;
212pub use subscription::*;
213pub use svg_renderer::*;
214pub(crate) use tab_stop::*;
215#[cfg(any(test, feature = "test-support"))]
216pub use test::*;
217pub use text_system::*;
218pub use util::{FluentBuilder, FutureExt, Timeout};
219pub use view::*;
220pub use window::*;
221
222#[cfg(not(target_family = "wasm"))]
223pub use pollster::block_on;
224
225/// Extension methods on [`Bounds`] that need to resolve the application's displays.
226///
227/// These live here rather than in `gpui_types` because they require [`App`], while
228/// the base [`Bounds`] type is defined in the platform-agnostic `gpui_types` crate.
229pub trait BoundsExt: Sized {
230    /// Generate a centered bounds for the given display or primary display if none is provided
231    fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self;
232
233    /// Generate maximized bounds for the given display or primary display if none is provided
234    fn maximized(display_id: Option<DisplayId>, cx: &App) -> Self;
235}
236
237impl BoundsExt for Bounds<Pixels> {
238    fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
239        let display = display_id
240            .and_then(|id| cx.find_display(id))
241            .or_else(|| cx.primary_display());
242
243        display
244            .map(|display| {
245                let visible_bounds = display.visible_bounds();
246                Bounds::centered_at(visible_bounds.center(), size.min(&visible_bounds.size))
247            })
248            .unwrap_or_else(|| Bounds {
249                origin: point(px(0.), px(0.)),
250                size,
251            })
252    }
253
254    fn maximized(display_id: Option<DisplayId>, cx: &App) -> Self {
255        let display = display_id
256            .and_then(|id| cx.find_display(id))
257            .or_else(|| cx.primary_display());
258
259        display
260            .map(|display| display.bounds())
261            .unwrap_or_else(|| Bounds {
262                origin: point(px(0.), px(0.)),
263                size: size(px(1024.), px(768.)),
264            })
265    }
266}
267
268impl HasRemSize for Window<'_> {
269    fn rem_size(&self) -> Pixels {
270        Window::rem_size(self)
271    }
272}
273
274/// The context trait, allows the different contexts in GPUI to be used
275/// interchangeably for certain operations.
276pub trait AppContext {
277    /// Create a new entity in the app context.
278    #[expect(
279        clippy::wrong_self_convention,
280        reason = "`App::new` is an ubiquitous function for creating entities"
281    )]
282    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
283
284    /// Reserve a slot for a entity to be inserted later.
285    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
286    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
287
288    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
289    ///
290    /// [`reserve_entity`]: Self::reserve_entity
291    fn insert_entity<T: 'static>(
292        &mut self,
293        reservation: Reservation<T>,
294        build_entity: impl FnOnce(&mut Context<T>) -> T,
295    ) -> Entity<T>;
296
297    /// Update a entity in the app context.
298    fn update_entity<T, R>(
299        &mut self,
300        handle: &Entity<T>,
301        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
302    ) -> R
303    where
304        T: 'static;
305
306    /// Update a entity in the app context.
307    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
308    where
309        T: 'static;
310
311    /// Read a entity from the app context.
312    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
313    where
314        T: 'static;
315
316    /// Update a window for the given handle.
317    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
318    where
319        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
320
321    /// Run `f` against the entity's *current* window — the most recently
322    /// rendered window that referenced the entity. Returns `None` if the
323    /// entity has no current window or that window is unavailable. See
324    /// [`App::with_window`] for the underlying lookup.
325    fn with_window<R>(
326        &mut self,
327        entity_id: EntityId,
328        f: impl FnOnce(&mut Window, &mut App) -> R,
329    ) -> Option<R>;
330
331    /// Read a window off of the application context.
332    fn read_window<T, R>(
333        &self,
334        window: &WindowHandle<T>,
335        read: impl FnOnce(Entity<T>, &App) -> R,
336    ) -> Result<R>
337    where
338        T: 'static;
339
340    /// Spawn a future on a background thread
341    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
342    where
343        R: Send + 'static;
344
345    /// Read a global from this app context
346    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
347    where
348        G: Global;
349}
350
351/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
352/// Allows you to obtain the [EntityId] for a entity before it is created.
353pub struct Reservation<T>(pub(crate) Slot<T>);
354
355impl<T: 'static> Reservation<T> {
356    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
357    pub fn entity_id(&self) -> EntityId {
358        self.0.entity_id()
359    }
360}
361
362/// This trait is used for the different visual contexts in GPUI that
363/// require a window to be present.
364pub trait VisualContext: AppContext {
365    /// The result type for window operations.
366    type Result<T>;
367
368    /// Returns the handle of the window associated with this context.
369    fn window_handle(&self) -> AnyWindowHandle;
370
371    /// Update a view with the given callback
372    fn update_window_entity<T: 'static, R>(
373        &mut self,
374        entity: &Entity<T>,
375        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
376    ) -> Self::Result<R>;
377
378    /// Create a new entity, with access to `Window`.
379    fn new_window_entity<T: 'static>(
380        &mut self,
381        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
382    ) -> Self::Result<Entity<T>>;
383
384    /// Replace the root view of a window with a new view.
385    fn replace_root_view<V>(
386        &mut self,
387        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
388    ) -> Self::Result<Entity<V>>
389    where
390        V: 'static + Render;
391
392    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
393    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
394    where
395        V: Focusable;
396}
397
398/// A trait for tying together the types of a GPUI entity and the events it can
399/// emit.
400pub trait EventEmitter<E: Any>: 'static {}
401
402/// A helper trait for auto-implementing certain methods on contexts that
403/// can be used interchangeably.
404pub trait BorrowAppContext {
405    /// Set a global value on the context.
406    fn set_global<T: Global>(&mut self, global: T);
407    /// Updates the global state of the given type.
408    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
409    where
410        G: Global;
411    /// Updates the global state of the given type, creating a default if it didn't exist before.
412    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
413    where
414        G: Global + Default;
415}
416
417impl<C> BorrowAppContext for C
418where
419    C: std::borrow::BorrowMut<App>,
420{
421    fn set_global<G: Global>(&mut self, global: G) {
422        self.borrow_mut().set_global(global)
423    }
424
425    #[track_caller]
426    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
427    where
428        G: Global,
429    {
430        let mut global = self.borrow_mut().lease_global::<G>();
431        let result = f(&mut global, self);
432        self.borrow_mut().end_global_lease(global);
433        result
434    }
435
436    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
437    where
438        G: Global + Default,
439    {
440        self.borrow_mut().default_global::<G>();
441        self.update_global(f)
442    }
443}