Skip to main content

gpui_core/
gpui.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
4#![allow(clippy::collapsible_else_if)] // False positives in platform specific code
5#![allow(unused_mut)] // False positives in platform specific code
6
7extern crate self as gpui;
8
9/// Absolute manifest directory used by backend build scripts for generated bindings.
10#[doc(hidden)]
11pub const GPUI_MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");
12
13#[macro_use]
14mod action;
15mod app;
16
17mod arena;
18mod asset_cache;
19mod assets;
20mod bounds_tree;
21mod color;
22/// The default colors used by GPUI.
23pub mod colors;
24mod element;
25mod elements;
26mod executor;
27mod geometry;
28mod global;
29mod input;
30mod inspector;
31mod interactive;
32mod key_dispatch;
33mod keymap;
34mod path_builder;
35mod platform;
36pub mod prelude;
37#[doc(hidden)]
38pub mod profiler;
39mod resource_profile;
40mod scene;
41mod shared_string;
42mod shared_uri;
43mod spring;
44mod style;
45mod styled;
46mod subscription;
47mod svg_renderer;
48mod tab_stop;
49mod taffy;
50#[cfg(any(test, feature = "test-support"))]
51pub mod test;
52mod text_system;
53mod util;
54mod view;
55mod window;
56
57#[cfg(doc)]
58pub mod _accessibility;
59#[cfg(doc)]
60pub mod _ownership_and_data_flow;
61
62/// Do not touch, here be dragons for use by gpui_macros and such.
63#[doc(hidden)]
64pub mod private {
65    pub use anyhow;
66    pub use inventory;
67    pub use schemars;
68    pub use serde;
69    pub use serde_json;
70}
71
72mod seal {
73    /// A mechanism for restricting implementations of a trait to only those in GPUI.
74    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
75    pub trait Sealed {}
76}
77
78pub use accesskit;
79pub use accesskit::Action as AccessibleAction;
80pub use accesskit::{Orientation, Role, Toggled};
81pub use action::*;
82pub use anyhow::Result;
83pub use app::*;
84pub(crate) use arena::*;
85pub use asset_cache::*;
86pub use assets::*;
87pub use color::*;
88pub use ctor::ctor;
89pub use element::*;
90pub use elements::*;
91pub use executor::*;
92pub use geometry::*;
93pub use global::*;
94pub use gpui_macros::{AppContext, IntoElement, Render, VisualContext, register_action, test};
95pub use http_client;
96pub use input::*;
97pub use inspector::*;
98pub use interactive::*;
99use key_dispatch::*;
100pub use keymap::*;
101pub use path_builder::*;
102pub use platform::*;
103pub use refineable::*;
104pub use resource_profile::*;
105pub use scene::*;
106pub use shared_string::*;
107pub use shared_uri::*;
108pub use smol::Timer;
109pub use spring::*;
110pub use style::*;
111pub use styled::*;
112pub use subscription::*;
113use svg_renderer::*;
114pub(crate) use tab_stop::*;
115pub use taffy::{AvailableSpace, LayoutId};
116#[cfg(any(test, feature = "test-support"))]
117pub use test::*;
118pub use text_system::*;
119#[cfg(any(test, feature = "test-support"))]
120pub use util::smol_timeout;
121pub use util::{FutureExt, Timeout, arc_cow::ArcCow};
122pub use view::*;
123pub use window::*;
124
125use std::{any::Any, borrow::BorrowMut, future::Future};
126use taffy::TaffyLayoutEngine;
127
128/// The context trait, allows the different contexts in GPUI to be used
129/// interchangeably for certain operations.
130pub trait AppContext {
131    /// The result type for this context, used for async contexts that
132    /// can't hold a direct reference to the application context.
133    type Result<T>;
134
135    /// Create a new entity in the app context.
136    #[expect(
137        clippy::wrong_self_convention,
138        reason = "`App::new` is an ubiquitous function for creating entities"
139    )]
140    fn new<T: 'static>(
141        &mut self,
142        build_entity: impl FnOnce(&mut Context<T>) -> T,
143    ) -> Self::Result<Entity<T>>;
144
145    /// Reserve a slot for a entity to be inserted later.
146    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
147    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
148
149    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
150    ///
151    /// [`reserve_entity`]: Self::reserve_entity
152    fn insert_entity<T: 'static>(
153        &mut self,
154        reservation: Reservation<T>,
155        build_entity: impl FnOnce(&mut Context<T>) -> T,
156    ) -> Self::Result<Entity<T>>;
157
158    /// Update a entity in the app context.
159    fn update_entity<T, R>(
160        &mut self,
161        handle: &Entity<T>,
162        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
163    ) -> Self::Result<R>
164    where
165        T: 'static;
166
167    /// Update a entity in the app context.
168    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
169    where
170        T: 'static;
171
172    /// Read a entity from the app context.
173    fn read_entity<T, R>(
174        &self,
175        handle: &Entity<T>,
176        read: impl FnOnce(&T, &App) -> R,
177    ) -> Self::Result<R>
178    where
179        T: 'static;
180
181    /// Update a window for the given handle.
182    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
183    where
184        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
185
186    /// Read a window off of the application context.
187    fn read_window<T, R>(
188        &self,
189        window: &WindowHandle<T>,
190        read: impl FnOnce(Entity<T>, &App) -> R,
191    ) -> Result<R>
192    where
193        T: 'static;
194
195    /// Spawn a future on a background thread
196    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
197    where
198        R: Send + 'static;
199
200    /// Read a global from this app context
201    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
202    where
203        G: Global;
204}
205
206/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
207/// Allows you to obtain the [EntityId] for a entity before it is created.
208pub struct Reservation<T>(pub(crate) Slot<T>);
209
210impl<T: 'static> Reservation<T> {
211    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
212    pub fn entity_id(&self) -> EntityId {
213        self.0.entity_id()
214    }
215}
216
217/// This trait is used for the different visual contexts in GPUI that
218/// require a window to be present.
219pub trait VisualContext: AppContext {
220    /// Returns the handle of the window associated with this context.
221    fn window_handle(&self) -> AnyWindowHandle;
222
223    /// Update a view with the given callback
224    fn update_window_entity<T: 'static, R>(
225        &mut self,
226        entity: &Entity<T>,
227        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
228    ) -> Self::Result<R>;
229
230    /// Create a new entity, with access to `Window`.
231    fn new_window_entity<T: 'static>(
232        &mut self,
233        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
234    ) -> Self::Result<Entity<T>>;
235
236    /// Replace the root view of a window with a new view.
237    fn replace_root_view<V>(
238        &mut self,
239        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
240    ) -> Self::Result<Entity<V>>
241    where
242        V: 'static + Render;
243
244    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
245    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
246    where
247        V: Focusable;
248}
249
250/// A trait for tying together the types of a GPUI entity and the events it can
251/// emit.
252pub trait EventEmitter<E: Any>: 'static {}
253
254/// A helper trait for auto-implementing certain methods on contexts that
255/// can be used interchangeably.
256pub trait BorrowAppContext {
257    /// Set a global value on the context.
258    fn set_global<T: Global>(&mut self, global: T);
259    /// Updates the global state of the given type.
260    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
261    where
262        G: Global;
263    /// Updates the global state of the given type, creating a default if it didn't exist before.
264    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
265    where
266        G: Global + Default;
267}
268
269impl<C> BorrowAppContext for C
270where
271    C: BorrowMut<App>,
272{
273    fn set_global<G: Global>(&mut self, global: G) {
274        self.borrow_mut().set_global(global)
275    }
276
277    #[track_caller]
278    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
279    where
280        G: Global,
281    {
282        let mut global = self.borrow_mut().lease_global::<G>();
283        let result = f(&mut global, self);
284        self.borrow_mut().end_global_lease(global);
285        result
286    }
287
288    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
289    where
290        G: Global + Default,
291    {
292        self.borrow_mut().default_global::<G>();
293        self.update_global(f)
294    }
295}
296
297/// A flatten equivalent for anyhow `Result`s.
298pub trait Flatten<T> {
299    /// Convert this type into a simple `Result<T>`.
300    fn flatten(self) -> Result<T>;
301}
302
303impl<T> Flatten<T> for Result<Result<T>> {
304    fn flatten(self) -> Result<T> {
305        self?
306    }
307}
308
309impl<T> Flatten<T> for Result<T> {
310    fn flatten(self) -> Result<T> {
311        self
312    }
313}
314
315/// Information about the GPU GPUI is running on.
316#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
317pub struct GpuSpecs {
318    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
319    pub is_software_emulated: bool,
320    /// The name of the device, as reported by Vulkan.
321    pub device_name: String,
322    /// The name of the driver, as reported by Vulkan.
323    pub driver_name: String,
324    /// Further information about the driver, as reported by Vulkan.
325    pub driver_info: String,
326}