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 [`App`]. You can create one with [`App::new`], and
 16//! kick off your application by passing a callback to [`App::run`]. Inside this callback,
 17//! you can create a new window with [`AppContext::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 Models. Whenever you need to store application state
 25//!   that communicates between different parts of your application, you'll want to use GPUI's
 26//!   models. Models are owned by GPUI and are only accessible through an owned smart pointer
 27//!   similar to an [`Rc`]. See the [`app::model_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 model that can be rendered, via 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//!   `elements`, 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 the [`action`] module for more information.
 52//! - Platform services, such as `quit the app` or `open a URL` are available as methods on the [`app::AppContext`].
 53//! - An async executor that is integrated with the platform's event loop. See the [`executor`] module for more information.,
 54//! - The [gpui::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://discord.gg/zed-community). 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;
 76mod element;
 77mod elements;
 78mod executor;
 79mod geometry;
 80mod global;
 81mod input;
 82mod interactive;
 83mod key_dispatch;
 84mod keymap;
 85mod platform;
 86pub mod prelude;
 87mod scene;
 88mod shared_string;
 89mod shared_uri;
 90mod style;
 91mod styled;
 92mod subscription;
 93mod svg_renderer;
 94mod taffy;
 95#[cfg(any(test, feature = "test-support"))]
 96pub mod test;
 97mod text_system;
 98mod util;
 99mod view;
100mod window;
101
102/// Do not touch, here be dragons for use by gpui_macros and such.
103#[doc(hidden)]
104pub mod private {
105    pub use linkme;
106    pub use serde;
107    pub use serde_derive;
108    pub use serde_json;
109}
110
111mod seal {
112    /// A mechanism for restricting implementations of a trait to only those in GPUI.
113    /// See: https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/
114    pub trait Sealed {}
115}
116
117pub use action::*;
118pub use anyhow::Result;
119pub use app::*;
120pub(crate) use arena::*;
121pub use asset_cache::*;
122pub use assets::*;
123pub use color::*;
124pub use ctor::ctor;
125pub use element::*;
126pub use elements::*;
127pub use executor::*;
128pub use geometry::*;
129pub use global::*;
130pub use gpui_macros::{register_action, test, IntoElement, Render};
131pub use input::*;
132pub use interactive::*;
133use key_dispatch::*;
134pub use keymap::*;
135pub use platform::*;
136pub use refineable::*;
137pub use scene::*;
138use seal::Sealed;
139pub use shared_string::*;
140pub use shared_uri::*;
141pub use smol::Timer;
142pub use style::*;
143pub use styled::*;
144pub use subscription::*;
145use svg_renderer::*;
146pub use taffy::{AvailableSpace, LayoutId};
147#[cfg(any(test, feature = "test-support"))]
148pub use test::*;
149pub use text_system::*;
150pub use util::arc_cow::ArcCow;
151pub use view::*;
152pub use window::*;
153
154use std::{any::Any, borrow::BorrowMut};
155use taffy::TaffyLayoutEngine;
156
157/// The context trait, allows the different contexts in GPUI to be used
158/// interchangeably for certain operations.
159pub trait Context {
160    /// The result type for this context, used for async contexts that
161    /// can't hold a direct reference to the application context.
162    type Result<T>;
163
164    /// Create a new model in the app context.
165    fn new_model<T: 'static>(
166        &mut self,
167        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
168    ) -> Self::Result<Model<T>>;
169
170    /// Reserve a slot for a model to be inserted later.
171    /// The returned [Reservation] allows you to obtain the [EntityId] for the future model.
172    fn reserve_model<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
173
174    /// Insert a new model in the app context based on a [Reservation] previously obtained from [`reserve_model`].
175    ///
176    /// [`reserve_model`]: Self::reserve_model
177    fn insert_model<T: 'static>(
178        &mut self,
179        reservation: Reservation<T>,
180        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
181    ) -> Self::Result<Model<T>>;
182
183    /// Update a model in the app context.
184    fn update_model<T, R>(
185        &mut self,
186        handle: &Model<T>,
187        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
188    ) -> Self::Result<R>
189    where
190        T: 'static;
191
192    /// Read a model from the app context.
193    fn read_model<T, R>(
194        &self,
195        handle: &Model<T>,
196        read: impl FnOnce(&T, &AppContext) -> R,
197    ) -> Self::Result<R>
198    where
199        T: 'static;
200
201    /// Update a window for the given handle.
202    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
203    where
204        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T;
205
206    /// Read a window off of the application context.
207    fn read_window<T, R>(
208        &self,
209        window: &WindowHandle<T>,
210        read: impl FnOnce(View<T>, &AppContext) -> R,
211    ) -> Result<R>
212    where
213        T: 'static;
214}
215
216/// Returned by [Context::reserve_model] to later be passed to [Context::insert_model].
217/// Allows you to obtain the [EntityId] for a model before it is created.
218pub struct Reservation<T>(pub(crate) Slot<T>);
219
220impl<T: 'static> Reservation<T> {
221    /// Returns the [EntityId] that will be associated with the model once it is inserted.
222    pub fn entity_id(&self) -> EntityId {
223        self.0.entity_id()
224    }
225}
226
227/// This trait is used for the different visual contexts in GPUI that
228/// require a window to be present.
229pub trait VisualContext: Context {
230    /// Construct a new view in the window referenced by this context.
231    fn new_view<V>(
232        &mut self,
233        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
234    ) -> Self::Result<View<V>>
235    where
236        V: 'static + Render;
237
238    /// Update a view with the given callback
239    fn update_view<V: 'static, R>(
240        &mut self,
241        view: &View<V>,
242        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
243    ) -> Self::Result<R>;
244
245    /// Replace the root view of a window with a new view.
246    fn replace_root_view<V>(
247        &mut self,
248        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
249    ) -> Self::Result<View<V>>
250    where
251        V: 'static + Render;
252
253    /// Focus a view in the window, if it implements the [`FocusableView`] trait.
254    fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
255    where
256        V: FocusableView;
257
258    /// Dismiss a view in the window, if it implements the [`ManagedView`] trait.
259    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
260    where
261        V: ManagedView;
262}
263
264/// A trait that allows models and views to be interchangeable in certain operations
265pub trait Entity<T>: Sealed {
266    /// The weak reference type for this entity.
267    type Weak: 'static;
268
269    /// The ID for this entity
270    fn entity_id(&self) -> EntityId;
271
272    /// Downgrade this entity to a weak reference.
273    fn downgrade(&self) -> Self::Weak;
274
275    /// Upgrade this entity from a weak reference.
276    fn upgrade_from(weak: &Self::Weak) -> Option<Self>
277    where
278        Self: Sized;
279}
280
281/// A trait for tying together the types of a GPUI entity and the events it can
282/// emit.
283pub trait EventEmitter<E: Any>: 'static {}
284
285/// A helper trait for auto-implementing certain methods on contexts that
286/// can be used interchangeably.
287pub trait BorrowAppContext {
288    /// Set a global value on the context.
289    fn set_global<T: Global>(&mut self, global: T);
290    /// Updates the global state of the given type.
291    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
292    where
293        G: Global;
294    /// Updates the global state of the given type, creating a default if it didn't exist before.
295    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
296    where
297        G: Global + Default;
298}
299
300impl<C> BorrowAppContext for C
301where
302    C: BorrowMut<AppContext>,
303{
304    fn set_global<G: Global>(&mut self, global: G) {
305        self.borrow_mut().set_global(global)
306    }
307
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#[derive(Default, Debug)]
346/// Information about the GPU GPUI is running on
347pub struct GPUSpecs {
348    /// true if the GPU is really a fake (like llvmpipe) running on the CPU
349    pub is_software_emulated: bool,
350    /// Name of the device as reported by vulkan
351    pub device_name: String,
352    /// Name of the driver as reported by vulkan
353    pub driver_name: String,
354    /// Further driver info as reported by vulkan
355    pub driver_info: String,
356}