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