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