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::*;
162pub use util::{FutureExt, Timeout, arc_cow::ArcCow};
163pub use view::*;
164pub use window::*;
165
166use std::{any::Any, borrow::BorrowMut, future::Future};
167use taffy::TaffyLayoutEngine;
168
169/// The context trait, allows the different contexts in GPUI to be used
170/// interchangeably for certain operations.
171pub trait AppContext {
172    /// The result type for this context, used for async contexts that
173    /// can't hold a direct reference to the application context.
174    type Result<T>;
175
176    /// Create a new entity in the app context.
177    #[expect(
178        clippy::wrong_self_convention,
179        reason = "`App::new` is an ubiquitous function for creating entities"
180    )]
181    fn new<T: 'static>(
182        &mut self,
183        build_entity: impl FnOnce(&mut Context<T>) -> T,
184    ) -> Self::Result<Entity<T>>;
185
186    /// Reserve a slot for a entity to be inserted later.
187    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
188    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
189
190    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
191    ///
192    /// [`reserve_entity`]: Self::reserve_entity
193    fn insert_entity<T: 'static>(
194        &mut self,
195        reservation: Reservation<T>,
196        build_entity: impl FnOnce(&mut Context<T>) -> T,
197    ) -> Self::Result<Entity<T>>;
198
199    /// Update a entity in the app context.
200    fn update_entity<T, R>(
201        &mut self,
202        handle: &Entity<T>,
203        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
204    ) -> Self::Result<R>
205    where
206        T: 'static;
207
208    /// Update a entity in the app context.
209    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
210    where
211        T: 'static;
212
213    /// Read a entity from the app context.
214    fn read_entity<T, R>(
215        &self,
216        handle: &Entity<T>,
217        read: impl FnOnce(&T, &App) -> R,
218    ) -> Self::Result<R>
219    where
220        T: 'static;
221
222    /// Update a window for the given handle.
223    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
224    where
225        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
226
227    /// Read a window off of the application context.
228    fn read_window<T, R>(
229        &self,
230        window: &WindowHandle<T>,
231        read: impl FnOnce(Entity<T>, &App) -> R,
232    ) -> Result<R>
233    where
234        T: 'static;
235
236    /// Spawn a future on a background thread
237    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
238    where
239        R: Send + 'static;
240
241    /// Read a global from this app context
242    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
243    where
244        G: Global;
245}
246
247/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
248/// Allows you to obtain the [EntityId] for a entity before it is created.
249pub struct Reservation<T>(pub(crate) Slot<T>);
250
251impl<T: 'static> Reservation<T> {
252    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
253    pub fn entity_id(&self) -> EntityId {
254        self.0.entity_id()
255    }
256}
257
258/// This trait is used for the different visual contexts in GPUI that
259/// require a window to be present.
260pub trait VisualContext: AppContext {
261    /// Returns the handle of the window associated with this context.
262    fn window_handle(&self) -> AnyWindowHandle;
263
264    /// Update a view with the given callback
265    fn update_window_entity<T: 'static, R>(
266        &mut self,
267        entity: &Entity<T>,
268        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
269    ) -> Self::Result<R>;
270
271    /// Create a new entity, with access to `Window`.
272    fn new_window_entity<T: 'static>(
273        &mut self,
274        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
275    ) -> Self::Result<Entity<T>>;
276
277    /// Replace the root view of a window with a new view.
278    fn replace_root_view<V>(
279        &mut self,
280        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
281    ) -> Self::Result<Entity<V>>
282    where
283        V: 'static + Render;
284
285    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
286    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
287    where
288        V: Focusable;
289}
290
291/// A trait for tying together the types of a GPUI entity and the events it can
292/// emit.
293pub trait EventEmitter<E: Any>: 'static {}
294
295/// A helper trait for auto-implementing certain methods on contexts that
296/// can be used interchangeably.
297pub trait BorrowAppContext {
298    /// Set a global value on the context.
299    fn set_global<T: Global>(&mut self, global: T);
300    /// Updates the global state of the given type.
301    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
302    where
303        G: Global;
304    /// Updates the global state of the given type, creating a default if it didn't exist before.
305    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
306    where
307        G: Global + Default;
308}
309
310impl<C> BorrowAppContext for C
311where
312    C: BorrowMut<App>,
313{
314    fn set_global<G: Global>(&mut self, global: G) {
315        self.borrow_mut().set_global(global)
316    }
317
318    #[track_caller]
319    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
320    where
321        G: Global,
322    {
323        let mut global = self.borrow_mut().lease_global::<G>();
324        let result = f(&mut global, self);
325        self.borrow_mut().end_global_lease(global);
326        result
327    }
328
329    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
330    where
331        G: Global + Default,
332    {
333        self.borrow_mut().default_global::<G>();
334        self.update_global(f)
335    }
336}
337
338/// A flatten equivalent for anyhow `Result`s.
339pub trait Flatten<T> {
340    /// Convert this type into a simple `Result<T>`.
341    fn flatten(self) -> Result<T>;
342}
343
344impl<T> Flatten<T> for Result<Result<T>> {
345    fn flatten(self) -> Result<T> {
346        self?
347    }
348}
349
350impl<T> Flatten<T> for Result<T> {
351    fn flatten(self) -> Result<T> {
352        self
353    }
354}
355
356/// Information about the GPU GPUI is running on.
357#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
358pub struct GpuSpecs {
359    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
360    pub is_software_emulated: bool,
361    /// The name of the device, as reported by Vulkan.
362    pub device_name: String,
363    /// The name of the driver, as reported by Vulkan.
364    pub driver_name: String,
365    /// Further information about the driver, as reported by Vulkan.
366    pub driver_info: String,
367}