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
5pub extern crate accesskit;
6pub extern crate http_client;
7#[cfg(any(test, feature = "test-support"))]
8pub extern crate proptest;
9/// Subsecond entry points for hot-patching callbacks outside GPUI's render boundaries.
10#[cfg(all(
11    feature = "hot-reload",
12    any(
13        target_os = "macos",
14        target_os = "linux",
15        target_os = "windows",
16        target_os = "ios"
17    )
18))]
19pub extern crate subsecond;
20
21extern crate self as gpui;
22
23pub mod colors;
24pub mod prelude;
25pub mod profiler;
26
27#[macro_use]
28mod action;
29mod app;
30mod app_effects;
31mod arena;
32mod asset_cache;
33mod assets;
34mod bounds_tree;
35mod color;
36mod effect_textures;
37mod element;
38mod elements;
39mod executor;
40mod geometry;
41mod gestures;
42mod global;
43mod input;
44mod inspector;
45mod interactive;
46mod key_dispatch;
47mod keymap;
48/// Optional embedder hooks for recording native drawing spans.
49pub mod native_profiling;
50mod path_builder;
51mod path_winding;
52mod platform;
53mod platform_scheduler;
54mod scene;
55mod shared_uri;
56mod spring;
57mod style;
58mod styled;
59mod subscription;
60mod svg_renderer;
61mod tab_stop;
62mod taffy;
63mod text_system;
64mod util;
65mod view;
66mod vn_clip;
67mod vn_effect_history;
68mod window;
69
70#[cfg(feature = "profiler")]
71mod debug_overlay;
72#[cfg(feature = "profiler")]
73pub use debug_overlay::*;
74
75#[cfg(gpui_hot_reload)]
76mod hot_reload;
77#[cfg(any(
78    test,
79    target_os = "windows",
80    target_os = "linux",
81    target_family = "wasm",
82    feature = "test-support",
83    feature = "bench-support"
84))]
85pub mod queue;
86
87#[cfg(any(test, feature = "bench-support"))]
88pub mod randomized_element_tree;
89
90#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
91mod bench;
92#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
93mod seeds;
94#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
95pub use seeds::calculate_seeds;
96
97#[cfg(any(test, feature = "test-support"))]
98pub mod test;
99#[cfg(any(test, feature = "test-support"))]
100pub use test::*;
101
102#[cfg(doc)]
103pub mod _accessibility;
104#[cfg(doc)]
105pub mod _ownership_and_data_flow;
106
107/// Do not touch, here be dragons for use by gpui_macros and such.
108#[doc(hidden)]
109pub mod private {
110    pub use anyhow;
111    pub use inventory;
112    pub use rand;
113    #[cfg(feature = "schemars")]
114    pub use schemars;
115    pub use serde;
116    pub use serde_json;
117}
118
119#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
120pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
121
122pub use accesskit::{Action as AccessibleAction, Orientation, Role, Toggled};
123pub use action::*;
124pub use anyhow::Result;
125pub use app::*;
126pub use app_effects::*;
127pub use asset_cache::*;
128pub use assets::*;
129pub use color::*;
130pub use effect_textures::*;
131pub use element::*;
132pub use elements::*;
133pub use executor::*;
134pub use geometry::*;
135pub use gestures::*;
136pub use global::*;
137pub use gpui_macros::{
138    AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
139};
140pub use gpui_shared_string::*;
141pub use gpui_util::arc_cow::ArcCow;
142pub use input::*;
143pub use inspector::*;
144pub use interactive::*;
145pub use keymap::*;
146pub use path_builder::*;
147pub(crate) use path_winding::*;
148pub use platform::*;
149pub use profiler::*;
150pub use refineable::*;
151pub use scene::*;
152pub use shared_uri::*;
153pub use spring::*;
154pub use style::Outline;
155pub use style::*;
156pub use styled::*;
157pub use subscription::*;
158pub use svg_renderer::*;
159pub use taffy::{AvailableSpace, LayoutId, VnRetainedLayoutStats};
160pub use text_system::*;
161pub use util::{FutureExt, Timeout};
162pub use view::*;
163pub use vn_clip::*;
164pub use vn_effect_history::*;
165pub use window::*;
166
167#[cfg(not(target_family = "wasm"))]
168pub use pollster::block_on;
169
170pub(crate) use arena::*;
171pub(crate) use platform_scheduler::PlatformScheduler;
172pub(crate) use tab_stop::*;
173
174use std::{any::Any, future::Future};
175
176use key_dispatch::*;
177
178mod seal {
179    /// A mechanism for restricting implementations of a trait to only those in GPUI.
180    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
181    pub trait Sealed {}
182}
183
184/// The context trait, allows the different contexts in GPUI to be used
185/// interchangeably for certain operations.
186pub trait AppContext {
187    /// Create a new entity in the app context.
188    #[expect(
189        clippy::wrong_self_convention,
190        reason = "`App::new` is an ubiquitous function for creating entities"
191    )]
192    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
193
194    /// Reserve a slot for a entity to be inserted later.
195    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
196    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
197
198    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
199    ///
200    /// [`reserve_entity`]: Self::reserve_entity
201    fn insert_entity<T: 'static>(
202        &mut self,
203        reservation: Reservation<T>,
204        build_entity: impl FnOnce(&mut Context<T>) -> T,
205    ) -> Entity<T>;
206
207    /// Update a entity in the app context.
208    fn update_entity<T, R>(
209        &mut self,
210        handle: &Entity<T>,
211        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
212    ) -> R
213    where
214        T: 'static;
215
216    /// Update a entity in the app context.
217    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
218    where
219        T: 'static;
220
221    /// Read a entity from the app context.
222    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
223    where
224        T: 'static;
225
226    /// Update a window for the given handle.
227    #[track_caller]
228    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
229    where
230        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
231
232    /// Run `f` against the entity's *current* window — the most recently
233    /// rendered window that referenced the entity. Returns `None` if the
234    /// entity has no current window or that window is unavailable. See
235    /// [`App::with_window`] for the underlying lookup.
236    fn with_window<R>(
237        &mut self,
238        entity_id: EntityId,
239        f: impl FnOnce(&mut Window, &mut App) -> R,
240    ) -> Option<R>;
241
242    /// Read a window off of the application context.
243    fn read_window<T, R>(
244        &self,
245        window: &WindowHandle<T>,
246        read: impl FnOnce(Entity<T>, &App) -> R,
247    ) -> Result<R>
248    where
249        T: 'static;
250
251    /// Spawn a future on a background thread
252    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
253    where
254        R: Send + 'static;
255
256    /// Read a global from this app context
257    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
258    where
259        G: Global;
260}
261
262/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
263/// Allows you to obtain the [EntityId] for a entity before it is created.
264pub struct Reservation<T>(pub(crate) Slot<T>);
265
266impl<T: 'static> Reservation<T> {
267    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
268    pub fn entity_id(&self) -> EntityId {
269        self.0.entity_id()
270    }
271}
272
273/// This trait is used for the different visual contexts in GPUI that
274/// require a window to be present.
275pub trait VisualContext: AppContext {
276    /// The result type for window operations.
277    type Result<T>;
278
279    /// Returns the handle of the window associated with this context.
280    fn window_handle(&self) -> AnyWindowHandle;
281
282    /// Update a view with the given callback
283    fn update_window_entity<T: 'static, R>(
284        &mut self,
285        entity: &Entity<T>,
286        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
287    ) -> Self::Result<R>;
288
289    /// Create a new entity, with access to `Window`.
290    fn new_window_entity<T: 'static>(
291        &mut self,
292        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
293    ) -> Self::Result<Entity<T>>;
294
295    /// Replace the root view of a window with a new view.
296    fn replace_root_view<V>(
297        &mut self,
298        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
299    ) -> Self::Result<Entity<V>>
300    where
301        V: 'static + Render;
302
303    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
304    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
305    where
306        V: Focusable;
307}
308
309/// A trait for tying together the types of a GPUI entity and the events it can
310/// emit.
311pub trait EventEmitter<E: Any>: 'static {}
312
313/// A helper trait for auto-implementing certain methods on contexts that
314/// can be used interchangeably.
315pub trait BorrowAppContext {
316    /// Set a global value on the context.
317    fn set_global<T: Global>(&mut self, global: T);
318    /// Updates the global state of the given type.
319    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
320    where
321        G: Global;
322    /// Updates the global state of the given type, creating a default if it didn't exist before.
323    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
324    where
325        G: Global + Default;
326}
327
328impl<C> BorrowAppContext for C
329where
330    C: std::borrow::BorrowMut<App>,
331{
332    fn set_global<G: Global>(&mut self, global: G) {
333        self.borrow_mut().set_global(global)
334    }
335
336    #[track_caller]
337    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
338    where
339        G: Global,
340    {
341        let mut global = self.borrow_mut().lease_global::<G>();
342        let result = f(&mut global, self);
343        self.borrow_mut().end_global_lease(global);
344        result
345    }
346
347    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
348    where
349        G: Global + Default,
350    {
351        self.borrow_mut().default_global::<G>();
352        self.update_global(f)
353    }
354}
355
356/// Information about the GPU GPUI is running on.
357#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
358pub struct GpuSpecs {
359    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
360    pub is_software_emulated: bool,
361    /// The name of the device, as reported by Vulkan.
362    pub device_name: String,
363    /// The name of the driver, as reported by Vulkan.
364    pub driver_name: String,
365    /// Further information about the driver, as reported by Vulkan.
366    pub driver_info: String,
367}