gpui.rs

  1//! # Welcome to GPUI!
  2//!
  3//! GPUI is a hybrid immediate and retained mode, GPU accelerated, UI framework
  4//! for Rust, designed to support a wide variety of applications.
  5//!
  6//! ## Getting Started
  7//!
  8//! GPUI is still in active development as we work on the Zed code editor and isn't yet on crates.io.
  9//! You'll also need to use the latest version of stable rust. Add the following to your Cargo.toml:
 10//!
 11//! ```toml
 12//! [dependencies]
 13//! gpui = { git = "https://github.com/zed-industries/zed" }
 14//! ```
 15//!
 16//! Everything in GPUI starts with an [`Application`]. You can create one with [`Application::new`], and
 17//! kick off your application by passing a callback to [`Application::run`]. Inside this callback,
 18//! you can create a new window with [`App::open_window`], and register your first root
 19//! view. See [gpui.rs](https://www.gpui.rs/) for a complete example.
 20//!
 21//! ## The Big Picture
 22//!
 23//! GPUI offers three different [registers](https://en.wikipedia.org/wiki/Register_(sociolinguistics)) depending on your needs:
 24//!
 25//! - State management and communication with [`Entity`]'s. Whenever you need to store application state
 26//!   that communicates between different parts of your application, you'll want to use GPUI's
 27//!   entities. Entities are owned by GPUI and are only accessible through an owned smart pointer
 28//!   similar to an [`std::rc::Rc`]. See [`app::Context`] for more information.
 29//!
 30//! - High level, declarative UI with views. All UI in GPUI starts with a view. A view is simply
 31//!   a [`Entity`] that can be rendered, by implementing the [`Render`] trait. At the start of each frame, GPUI
 32//!   will call this render method on the root view of a given window. Views build a tree of
 33//!   [`Element`]s, lay them out and style them with a tailwind-style API, and then give them to
 34//!   GPUI to turn into pixels. See the [`elements::Div`] element for an all purpose swiss-army
 35//!   knife for UI.
 36//!
 37//! - Low level, imperative UI with Elements. Elements are the building blocks of UI in GPUI, and they
 38//!   provide a nice wrapper around an imperative API that provides as much flexibility and control as
 39//!   you need. Elements have total control over how they and their child elements are rendered and
 40//!   can be used for making efficient views into large lists, implement custom layouting for a code editor,
 41//!   and anything else you can think of. See the [`elements`] module for more information.
 42//!
 43//!  Each of these registers has one or more corresponding contexts that can be accessed from all GPUI services.
 44//!  This context is your main interface to GPUI, and is used extensively throughout the framework.
 45//!
 46//! ## Other Resources
 47//!
 48//! In addition to the systems above, GPUI provides a range of smaller services that are useful for building
 49//! complex applications:
 50//!
 51//! - Actions are user-defined structs that are used for converting keystrokes into logical operations in your UI.
 52//!   Use this for implementing keyboard shortcuts, such as cmd-q (See `action` module for more information).
 53//! - Platform services, such as `quit the app` or `open a URL` are available as methods on the [`app::App`].
 54//! - An async executor that is integrated with the platform's event loop. See the [`executor`] module for more information.,
 55//! - The [`gpui::test`](macro@test) macro provides a convenient way to write tests for your GPUI applications. Tests also have their
 56//!   own kind of context, a [`TestAppContext`] which provides ways of simulating common platform input. See [`TestAppContext`]
 57//!   and [`mod@test`] modules for more details.
 58//!
 59//! Currently, the best way to learn about these APIs is to read the Zed source code, ask us about it at a fireside hack, or drop
 60//! a question in the [Zed Discord](https://zed.dev/community-links). We're working on improving the documentation, creating more examples,
 61//! and will be publishing more guides to GPUI on our [blog](https://zed.dev/blog).
 62
 63#![deny(missing_docs)]
 64#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
 65#![allow(clippy::collapsible_else_if)] // False positives in platform specific code
 66#![allow(unused_mut)] // False positives in platform specific code
 67
 68#[macro_use]
 69mod action;
 70mod app;
 71
 72mod arena;
 73mod asset_cache;
 74mod assets;
 75mod bounds_tree;
 76mod color;
 77/// The default colors used by GPUI.
 78pub mod colors;
 79mod element;
 80mod elements;
 81mod executor;
 82mod geometry;
 83mod global;
 84mod input;
 85mod inspector;
 86mod interactive;
 87mod key_dispatch;
 88mod keymap;
 89mod path_builder;
 90mod platform;
 91pub mod prelude;
 92mod scene;
 93mod shared_string;
 94mod shared_uri;
 95mod style;
 96mod styled;
 97mod subscription;
 98mod svg_renderer;
 99mod tab_stop;
100mod taffy;
101#[cfg(any(test, feature = "test-support"))]
102pub mod test;
103mod text_system;
104mod util;
105mod view;
106mod window;
107
108/// Do not touch, here be dragons for use by gpui_macros and such.
109#[doc(hidden)]
110pub mod private {
111    pub use anyhow;
112    pub use inventory;
113    pub use schemars;
114    pub use serde;
115    pub use serde_json;
116}
117
118mod seal {
119    /// A mechanism for restricting implementations of a trait to only those in GPUI.
120    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
121    pub trait Sealed {}
122}
123
124pub use action::*;
125pub use anyhow::Result;
126pub use app::*;
127pub(crate) use arena::*;
128pub use asset_cache::*;
129pub use assets::*;
130pub use color::*;
131pub use ctor::ctor;
132pub use element::*;
133pub use elements::*;
134pub use executor::*;
135pub use geometry::*;
136pub use global::*;
137pub use gpui_macros::{AppContext, IntoElement, Render, VisualContext, register_action, test};
138pub use http_client;
139pub use input::*;
140pub use inspector::*;
141pub use interactive::*;
142use key_dispatch::*;
143pub use keymap::*;
144pub use path_builder::*;
145pub use platform::*;
146pub use refineable::*;
147pub use scene::*;
148pub use shared_string::*;
149pub use shared_uri::*;
150pub use smol::Timer;
151pub use style::*;
152pub use styled::*;
153pub use subscription::*;
154use svg_renderer::*;
155pub(crate) use tab_stop::*;
156pub use taffy::{AvailableSpace, LayoutId};
157#[cfg(any(test, feature = "test-support"))]
158pub use test::*;
159pub use text_system::*;
160pub use util::{FutureExt, Timeout, arc_cow::ArcCow};
161pub use view::*;
162pub use window::*;
163
164use std::{any::Any, borrow::BorrowMut, future::Future};
165use taffy::TaffyLayoutEngine;
166
167/// The context trait, allows the different contexts in GPUI to be used
168/// interchangeably for certain operations.
169pub trait AppContext {
170    /// The result type for this context, used for async contexts that
171    /// can't hold a direct reference to the application context.
172    type Result<T>;
173
174    /// Create a new entity in the app context.
175    #[expect(
176        clippy::wrong_self_convention,
177        reason = "`App::new` is an ubiquitous function for creating entities"
178    )]
179    fn new<T: 'static>(
180        &mut self,
181        build_entity: impl FnOnce(&mut Context<T>) -> T,
182    ) -> Self::Result<Entity<T>>;
183
184    /// Reserve a slot for a entity to be inserted later.
185    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
186    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
187
188    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
189    ///
190    /// [`reserve_entity`]: Self::reserve_entity
191    fn insert_entity<T: 'static>(
192        &mut self,
193        reservation: Reservation<T>,
194        build_entity: impl FnOnce(&mut Context<T>) -> T,
195    ) -> Self::Result<Entity<T>>;
196
197    /// Update a entity in the app context.
198    fn update_entity<T, R>(
199        &mut self,
200        handle: &Entity<T>,
201        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
202    ) -> Self::Result<R>
203    where
204        T: 'static;
205
206    /// Update a entity in the app context.
207    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
208    where
209        T: 'static;
210
211    /// Read a entity from the app context.
212    fn read_entity<T, R>(
213        &self,
214        handle: &Entity<T>,
215        read: impl FnOnce(&T, &App) -> R,
216    ) -> Self::Result<R>
217    where
218        T: 'static;
219
220    /// Update a window for the given handle.
221    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
222    where
223        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
224
225    /// Read a window off of the application context.
226    fn read_window<T, R>(
227        &self,
228        window: &WindowHandle<T>,
229        read: impl FnOnce(Entity<T>, &App) -> R,
230    ) -> Result<R>
231    where
232        T: 'static;
233
234    /// Spawn a future on a background thread
235    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
236    where
237        R: Send + 'static;
238
239    /// Read a global from this app context
240    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
241    where
242        G: Global;
243}
244
245/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
246/// Allows you to obtain the [EntityId] for a entity before it is created.
247pub struct Reservation<T>(pub(crate) Slot<T>);
248
249impl<T: 'static> Reservation<T> {
250    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
251    pub fn entity_id(&self) -> EntityId {
252        self.0.entity_id()
253    }
254}
255
256/// This trait is used for the different visual contexts in GPUI that
257/// require a window to be present.
258pub trait VisualContext: AppContext {
259    /// Returns the handle of the window associated with this context.
260    fn window_handle(&self) -> AnyWindowHandle;
261
262    /// Update a view with the given callback
263    fn update_window_entity<T: 'static, R>(
264        &mut self,
265        entity: &Entity<T>,
266        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
267    ) -> Self::Result<R>;
268
269    /// Create a new entity, with access to `Window`.
270    fn new_window_entity<T: 'static>(
271        &mut self,
272        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
273    ) -> Self::Result<Entity<T>>;
274
275    /// Replace the root view of a window with a new view.
276    fn replace_root_view<V>(
277        &mut self,
278        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
279    ) -> Self::Result<Entity<V>>
280    where
281        V: 'static + Render;
282
283    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
284    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
285    where
286        V: Focusable;
287}
288
289/// A trait for tying together the types of a GPUI entity and the events it can
290/// emit.
291pub trait EventEmitter<E: Any>: 'static {}
292
293/// A helper trait for auto-implementing certain methods on contexts that
294/// can be used interchangeably.
295pub trait BorrowAppContext {
296    /// Set a global value on the context.
297    fn set_global<T: Global>(&mut self, global: T);
298    /// Updates the global state of the given type.
299    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
300    where
301        G: Global;
302    /// Updates the global state of the given type, creating a default if it didn't exist before.
303    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
304    where
305        G: Global + Default;
306}
307
308impl<C> BorrowAppContext for C
309where
310    C: BorrowMut<App>,
311{
312    fn set_global<G: Global>(&mut self, global: G) {
313        self.borrow_mut().set_global(global)
314    }
315
316    #[track_caller]
317    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
318    where
319        G: Global,
320    {
321        let mut global = self.borrow_mut().lease_global::<G>();
322        let result = f(&mut global, self);
323        self.borrow_mut().end_global_lease(global);
324        result
325    }
326
327    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
328    where
329        G: Global + Default,
330    {
331        self.borrow_mut().default_global::<G>();
332        self.update_global(f)
333    }
334}
335
336/// A flatten equivalent for anyhow `Result`s.
337pub trait Flatten<T> {
338    /// Convert this type into a simple `Result<T>`.
339    fn flatten(self) -> Result<T>;
340}
341
342impl<T> Flatten<T> for Result<Result<T>> {
343    fn flatten(self) -> Result<T> {
344        self?
345    }
346}
347
348impl<T> Flatten<T> for Result<T> {
349    fn flatten(self) -> Result<T> {
350        self
351    }
352}
353
354/// Information about the GPU GPUI is running on.
355#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
356pub struct GpuSpecs {
357    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
358    pub is_software_emulated: bool,
359    /// The name of the device, as reported by Vulkan.
360    pub device_name: String,
361    /// The name of the driver, as reported by Vulkan.
362    pub driver_name: String,
363    /// Further information about the driver, as reported by Vulkan.
364    pub driver_info: String,
365}