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#[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    time::Instant,
118};
119use taffy::TaffyLayoutEngine;
120
121/// The context trait, allows the different contexts in GPUI to be used
122/// interchangeably for certain operations.
123pub trait AppContext {
124    /// The result type for this context, used for async contexts that
125    /// can't hold a direct reference to the application context.
126    type Result<T>;
127
128    /// Create a new entity in the app context.
129    #[expect(
130        clippy::wrong_self_convention,
131        reason = "`App::new` is an ubiquitous function for creating entities"
132    )]
133    fn new<T: 'static>(
134        &mut self,
135        build_entity: impl FnOnce(&mut Context<T>) -> T,
136    ) -> Self::Result<Entity<T>>;
137
138    /// Reserve a slot for a entity to be inserted later.
139    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
140    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
141
142    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
143    ///
144    /// [`reserve_entity`]: Self::reserve_entity
145    fn insert_entity<T: 'static>(
146        &mut self,
147        reservation: Reservation<T>,
148        build_entity: impl FnOnce(&mut Context<T>) -> T,
149    ) -> Self::Result<Entity<T>>;
150
151    /// Update a entity in the app context.
152    fn update_entity<T, R>(
153        &mut self,
154        handle: &Entity<T>,
155        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
156    ) -> Self::Result<R>
157    where
158        T: 'static;
159
160    /// Update a entity in the app context.
161    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
162    where
163        T: 'static;
164
165    /// Read a entity from the app context.
166    fn read_entity<T, R>(
167        &self,
168        handle: &Entity<T>,
169        read: impl FnOnce(&T, &App) -> R,
170    ) -> Self::Result<R>
171    where
172        T: 'static;
173
174    /// Update a window for the given handle.
175    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
176    where
177        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
178
179    /// Read a window off of the application context.
180    fn read_window<T, R>(
181        &self,
182        window: &WindowHandle<T>,
183        read: impl FnOnce(Entity<T>, &App) -> R,
184    ) -> Result<R>
185    where
186        T: 'static;
187
188    /// Spawn a future on a background thread
189    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
190    where
191        R: Send + 'static;
192
193    /// Read a global from this app context
194    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
195    where
196        G: Global;
197}
198
199/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
200/// Allows you to obtain the [EntityId] for a entity before it is created.
201pub struct Reservation<T>(pub(crate) Slot<T>);
202
203impl<T: 'static> Reservation<T> {
204    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
205    pub fn entity_id(&self) -> EntityId {
206        self.0.entity_id()
207    }
208}
209
210/// This trait is used for the different visual contexts in GPUI that
211/// require a window to be present.
212pub trait VisualContext: AppContext {
213    /// Returns the handle of the window associated with this context.
214    fn window_handle(&self) -> AnyWindowHandle;
215
216    /// Update a view with the given callback
217    fn update_window_entity<T: 'static, R>(
218        &mut self,
219        entity: &Entity<T>,
220        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
221    ) -> Self::Result<R>;
222
223    /// Create a new entity, with access to `Window`.
224    fn new_window_entity<T: 'static>(
225        &mut self,
226        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
227    ) -> Self::Result<Entity<T>>;
228
229    /// Replace the root view of a window with a new view.
230    fn replace_root_view<V>(
231        &mut self,
232        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
233    ) -> Self::Result<Entity<V>>
234    where
235        V: 'static + Render;
236
237    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
238    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
239    where
240        V: Focusable;
241}
242
243/// A trait for tying together the types of a GPUI entity and the events it can
244/// emit.
245pub trait EventEmitter<E: Any>: 'static {}
246
247/// A helper trait for auto-implementing certain methods on contexts that
248/// can be used interchangeably.
249pub trait BorrowAppContext {
250    /// Set a global value on the context.
251    fn set_global<T: Global>(&mut self, global: T);
252    /// Updates the global state of the given type.
253    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
254    where
255        G: Global;
256    /// Updates the global state of the given type, creating a default if it didn't exist before.
257    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
258    where
259        G: Global + Default;
260}
261
262impl<C> BorrowAppContext for C
263where
264    C: BorrowMut<App>,
265{
266    fn set_global<G: Global>(&mut self, global: G) {
267        self.borrow_mut().set_global(global)
268    }
269
270    #[track_caller]
271    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
272    where
273        G: Global,
274    {
275        let mut global = self.borrow_mut().lease_global::<G>();
276        let result = f(&mut global, self);
277        self.borrow_mut().end_global_lease(global);
278        result
279    }
280
281    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
282    where
283        G: Global + Default,
284    {
285        self.borrow_mut().default_global::<G>();
286        self.update_global(f)
287    }
288}
289
290/// A flatten equivalent for anyhow `Result`s.
291pub trait Flatten<T> {
292    /// Convert this type into a simple `Result<T>`.
293    fn flatten(self) -> Result<T>;
294}
295
296impl<T> Flatten<T> for Result<Result<T>> {
297    fn flatten(self) -> Result<T> {
298        self?
299    }
300}
301
302impl<T> Flatten<T> for Result<T> {
303    fn flatten(self) -> Result<T> {
304        self
305    }
306}
307
308/// Information about the GPU GPUI is running on.
309#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
310pub struct GpuSpecs {
311    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
312    pub is_software_emulated: bool,
313    /// The name of the device, as reported by Vulkan.
314    pub device_name: String,
315    /// The name of the driver, as reported by Vulkan.
316    pub driver_name: String,
317    /// Further information about the driver, as reported by Vulkan.
318    pub driver_info: String,
319}
320
321pub(crate) static FRAME_INDEX: AtomicUsize = AtomicUsize::new(0);
322
323/// A
324#[derive(Debug, Clone)]
325pub struct FrameTimings {
326    /// A
327    pub frame_time: f64,
328    /// A
329    pub timings: HashMap<&'static core::panic::Location<'static>, f64>,
330    /// A
331    pub end_time: Option<Instant>,
332}
333
334/// TESTING
335pub static FRAME_RING: usize = 240;
336pub(crate) static FRAME_BUF: LazyLock<[Arc<Mutex<FrameTimings>>; FRAME_RING]> =
337    LazyLock::new(|| {
338        core::array::from_fn(|_| {
339            Arc::new(Mutex::new(FrameTimings {
340                frame_time: 0.0,
341                timings: HashMap::default(),
342                end_time: None,
343            }))
344        })
345    });
346
347/// A
348pub fn get_frame_timings() -> FrameTimings {
349    FRAME_BUF
350        [(FRAME_INDEX.load(std::sync::atomic::Ordering::Acquire) % FRAME_RING).saturating_sub(1)]
351    .lock()
352    .clone()
353}
354
355/// A
356pub fn get_all_timings() -> (Vec<FrameTimings>, usize) {
357    let frame_index = FRAME_INDEX.load(std::sync::atomic::Ordering::Acquire) % FRAME_RING;
358    (
359        FRAME_BUF.iter().map(|frame| frame.lock().clone()).collect(),
360        frame_index,
361    )
362}