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