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