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
 68extern crate self as gpui;
 69
 70#[macro_use]
 71mod action;
 72mod app;
 73
 74mod arena;
 75mod asset_cache;
 76mod assets;
 77mod bounds_tree;
 78mod color;
 79/// The default colors used by GPUI.
 80pub mod colors;
 81mod element;
 82mod elements;
 83mod executor;
 84mod geometry;
 85mod global;
 86mod input;
 87mod inspector;
 88mod interactive;
 89mod key_dispatch;
 90mod keymap;
 91mod path_builder;
 92mod platform;
 93pub mod prelude;
 94mod scene;
 95mod shared_string;
 96mod shared_uri;
 97mod style;
 98mod styled;
 99mod subscription;
100mod svg_renderer;
101mod tab_stop;
102mod taffy;
103#[cfg(any(test, feature = "test-support"))]
104pub mod test;
105mod text_system;
106mod util;
107mod view;
108mod window;
109
110/// Do not touch, here be dragons for use by gpui_macros and such.
111#[doc(hidden)]
112pub mod private {
113    pub use anyhow;
114    pub use inventory;
115    pub use schemars;
116    pub use serde;
117    pub use serde_json;
118}
119
120mod seal {
121    /// A mechanism for restricting implementations of a trait to only those in GPUI.
122    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
123    pub trait Sealed {}
124}
125
126pub use action::*;
127pub use anyhow::Result;
128pub use app::*;
129pub(crate) use arena::*;
130pub use asset_cache::*;
131pub use assets::*;
132pub use color::*;
133pub use ctor::ctor;
134pub use element::*;
135pub use elements::*;
136pub use executor::*;
137pub use geometry::*;
138pub use global::*;
139pub use gpui_macros::{AppContext, IntoElement, Render, VisualContext, register_action, test};
140pub use http_client;
141pub use input::*;
142pub use inspector::*;
143pub use interactive::*;
144use key_dispatch::*;
145pub use keymap::*;
146pub use path_builder::*;
147pub use platform::*;
148pub use refineable::*;
149pub use scene::*;
150pub use shared_string::*;
151pub use shared_uri::*;
152pub use smol::Timer;
153pub use style::*;
154pub use styled::*;
155pub use subscription::*;
156use svg_renderer::*;
157pub(crate) use tab_stop::*;
158pub use taffy::{AvailableSpace, LayoutId};
159#[cfg(any(test, feature = "test-support"))]
160pub use test::*;
161pub use text_system::*;
162#[cfg(any(test, feature = "test-support"))]
163pub use util::smol_timeout;
164pub use util::{FutureExt, Timeout, arc_cow::ArcCow};
165pub use view::*;
166pub use window::*;
167
168use std::{any::Any, borrow::BorrowMut, future::Future};
169use taffy::TaffyLayoutEngine;
170
171/// The context trait, allows the different contexts in GPUI to be used
172/// interchangeably for certain operations.
173pub trait AppContext {
174    /// The result type for this context, used for async contexts that
175    /// can't hold a direct reference to the application context.
176    type Result<T>;
177
178    /// Create a new entity in the app context.
179    #[expect(
180        clippy::wrong_self_convention,
181        reason = "`App::new` is an ubiquitous function for creating entities"
182    )]
183    fn new<T: 'static>(
184        &mut self,
185        build_entity: impl FnOnce(&mut Context<T>) -> T,
186    ) -> Self::Result<Entity<T>>;
187
188    /// Reserve a slot for a entity to be inserted later.
189    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
190    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
191
192    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
193    ///
194    /// [`reserve_entity`]: Self::reserve_entity
195    fn insert_entity<T: 'static>(
196        &mut self,
197        reservation: Reservation<T>,
198        build_entity: impl FnOnce(&mut Context<T>) -> T,
199    ) -> Self::Result<Entity<T>>;
200
201    /// Update a entity in the app context.
202    fn update_entity<T, R>(
203        &mut self,
204        handle: &Entity<T>,
205        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
206    ) -> Self::Result<R>
207    where
208        T: 'static;
209
210    /// Update a entity in the app context.
211    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
212    where
213        T: 'static;
214
215    /// Read a entity from the app context.
216    fn read_entity<T, R>(
217        &self,
218        handle: &Entity<T>,
219        read: impl FnOnce(&T, &App) -> R,
220    ) -> Self::Result<R>
221    where
222        T: 'static;
223
224    /// Update a window for the given handle.
225    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
226    where
227        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
228
229    /// Read a window off of the application context.
230    fn read_window<T, R>(
231        &self,
232        window: &WindowHandle<T>,
233        read: impl FnOnce(Entity<T>, &App) -> R,
234    ) -> Result<R>
235    where
236        T: 'static;
237
238    /// Spawn a future on a background thread
239    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
240    where
241        R: Send + 'static;
242
243    /// Read a global from this app context
244    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
245    where
246        G: Global;
247}
248
249/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
250/// Allows you to obtain the [EntityId] for a entity before it is created.
251pub struct Reservation<T>(pub(crate) Slot<T>);
252
253impl<T: 'static> Reservation<T> {
254    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
255    pub fn entity_id(&self) -> EntityId {
256        self.0.entity_id()
257    }
258}
259
260/// This trait is used for the different visual contexts in GPUI that
261/// require a window to be present.
262pub trait VisualContext: AppContext {
263    /// Returns the handle of the window associated with this context.
264    fn window_handle(&self) -> AnyWindowHandle;
265
266    /// Update a view with the given callback
267    fn update_window_entity<T: 'static, R>(
268        &mut self,
269        entity: &Entity<T>,
270        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
271    ) -> Self::Result<R>;
272
273    /// Create a new entity, with access to `Window`.
274    fn new_window_entity<T: 'static>(
275        &mut self,
276        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
277    ) -> Self::Result<Entity<T>>;
278
279    /// Replace the root view of a window with a new view.
280    fn replace_root_view<V>(
281        &mut self,
282        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
283    ) -> Self::Result<Entity<V>>
284    where
285        V: 'static + Render;
286
287    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
288    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
289    where
290        V: Focusable;
291}
292
293/// A trait for tying together the types of a GPUI entity and the events it can
294/// emit.
295pub trait EventEmitter<E: Any>: 'static {}
296
297/// A helper trait for auto-implementing certain methods on contexts that
298/// can be used interchangeably.
299pub trait BorrowAppContext {
300    /// Set a global value on the context.
301    fn set_global<T: Global>(&mut self, global: T);
302    /// Updates the global state of the given type.
303    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
304    where
305        G: Global;
306    /// Updates the global state of the given type, creating a default if it didn't exist before.
307    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
308    where
309        G: Global + Default;
310}
311
312impl<C> BorrowAppContext for C
313where
314    C: BorrowMut<App>,
315{
316    fn set_global<G: Global>(&mut self, global: G) {
317        self.borrow_mut().set_global(global)
318    }
319
320    #[track_caller]
321    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
322    where
323        G: Global,
324    {
325        let mut global = self.borrow_mut().lease_global::<G>();
326        let result = f(&mut global, self);
327        self.borrow_mut().end_global_lease(global);
328        result
329    }
330
331    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
332    where
333        G: Global + Default,
334    {
335        self.borrow_mut().default_global::<G>();
336        self.update_global(f)
337    }
338}
339
340/// A flatten equivalent for anyhow `Result`s.
341pub trait Flatten<T> {
342    /// Convert this type into a simple `Result<T>`.
343    fn flatten(self) -> Result<T>;
344}
345
346impl<T> Flatten<T> for Result<Result<T>> {
347    fn flatten(self) -> Result<T> {
348        self?
349    }
350}
351
352impl<T> Flatten<T> for Result<T> {
353    fn flatten(self) -> Result<T> {
354        self
355    }
356}
357
358/// Information about the GPU GPUI is running on.
359#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
360pub struct GpuSpecs {
361    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
362    pub is_software_emulated: bool,
363    /// The name of the device, as reported by Vulkan.
364    pub device_name: String,
365    /// The name of the driver, as reported by Vulkan.
366    pub driver_name: String,
367    /// Further information about the driver, as reported by Vulkan.
368    pub driver_info: String,
369}