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