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