Skip to main content

gpui/
gpui.rs

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