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