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