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