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