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