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