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