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/U4qhCEhMXP). 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 input;
 81mod interactive;
 82mod key_dispatch;
 83mod keymap;
 84mod platform;
 85pub mod prelude;
 86mod scene;
 87mod shared_string;
 88mod shared_uri;
 89mod style;
 90mod styled;
 91mod subscription;
 92mod svg_renderer;
 93mod taffy;
 94#[cfg(any(test, feature = "test-support"))]
 95pub mod test;
 96mod text_system;
 97mod util;
 98mod view;
 99mod window;
100
101/// Do not touch, here be dragons for use by gpui_macros and such.
102#[doc(hidden)]
103pub mod private {
104    pub use linkme;
105    pub use serde;
106    pub use serde_derive;
107    pub use serde_json;
108}
109
110mod seal {
111    /// A mechanism for restricting implementations of a trait to only those in GPUI.
112    /// See: https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/
113    pub trait Sealed {}
114}
115
116pub use action::*;
117pub use anyhow::Result;
118pub use app::*;
119pub(crate) use arena::*;
120pub use asset_cache::*;
121pub use assets::*;
122pub use color::*;
123pub use ctor::ctor;
124pub use element::*;
125pub use elements::*;
126pub use executor::*;
127pub use geometry::*;
128pub use gpui_macros::{register_action, test, IntoElement, Render};
129pub use input::*;
130pub use interactive::*;
131use key_dispatch::*;
132pub use keymap::*;
133pub use platform::*;
134pub use refineable::*;
135pub use scene::*;
136use seal::Sealed;
137pub use shared_string::*;
138pub use shared_uri::*;
139pub use smol::Timer;
140pub use style::*;
141pub use styled::*;
142pub use subscription::*;
143use svg_renderer::*;
144pub use taffy::{AvailableSpace, LayoutId};
145#[cfg(any(test, feature = "test-support"))]
146pub use test::*;
147pub use text_system::*;
148pub use util::arc_cow::ArcCow;
149pub use view::*;
150pub use window::*;
151
152use std::{any::Any, borrow::BorrowMut};
153use taffy::TaffyLayoutEngine;
154
155/// The context trait, allows the different contexts in GPUI to be used
156/// interchangeably for certain operations.
157pub trait Context {
158    /// The result type for this context, used for async contexts that
159    /// can't hold a direct reference to the application context.
160    type Result<T>;
161
162    /// Create a new model in the app context.
163    fn new_model<T: 'static>(
164        &mut self,
165        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
166    ) -> Self::Result<Model<T>>;
167
168    /// Update a model in the app context.
169    fn update_model<T, R>(
170        &mut self,
171        handle: &Model<T>,
172        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
173    ) -> Self::Result<R>
174    where
175        T: 'static;
176
177    /// Read a model from the app context.
178    fn read_model<T, R>(
179        &self,
180        handle: &Model<T>,
181        read: impl FnOnce(&T, &AppContext) -> R,
182    ) -> Self::Result<R>
183    where
184        T: 'static;
185
186    /// Update a window for the given handle.
187    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
188    where
189        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T;
190
191    /// Read a window off of the application context.
192    fn read_window<T, R>(
193        &self,
194        window: &WindowHandle<T>,
195        read: impl FnOnce(View<T>, &AppContext) -> R,
196    ) -> Result<R>
197    where
198        T: 'static;
199}
200
201/// This trait is used for the different visual contexts in GPUI that
202/// require a window to be present.
203pub trait VisualContext: Context {
204    /// Construct a new view in the window referenced by this context.
205    fn new_view<V>(
206        &mut self,
207        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
208    ) -> Self::Result<View<V>>
209    where
210        V: 'static + Render;
211
212    /// Update a view with the given callback
213    fn update_view<V: 'static, R>(
214        &mut self,
215        view: &View<V>,
216        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
217    ) -> Self::Result<R>;
218
219    /// Replace the root view of a window with a new view.
220    fn replace_root_view<V>(
221        &mut self,
222        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
223    ) -> Self::Result<View<V>>
224    where
225        V: 'static + Render;
226
227    /// Focus a view in the window, if it implements the [`FocusableView`] trait.
228    fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
229    where
230        V: FocusableView;
231
232    /// Dismiss a view in the window, if it implements the [`ManagedView`] trait.
233    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
234    where
235        V: ManagedView;
236}
237
238/// A trait that allows models and views to be interchangeable in certain operations
239pub trait Entity<T>: Sealed {
240    /// The weak reference type for this entity.
241    type Weak: 'static;
242
243    /// The ID for this entity
244    fn entity_id(&self) -> EntityId;
245
246    /// Downgrade this entity to a weak reference.
247    fn downgrade(&self) -> Self::Weak;
248
249    /// Upgrade this entity from a weak reference.
250    fn upgrade_from(weak: &Self::Weak) -> Option<Self>
251    where
252        Self: Sized;
253}
254
255/// A trait for tying together the types of a GPUI entity and the events it can
256/// emit.
257pub trait EventEmitter<E: Any>: 'static {}
258
259/// A helper trait for auto-implementing certain methods on contexts that
260/// can be used interchangeably.
261pub trait BorrowAppContext {
262    /// Set a global value on the context.
263    fn set_global<T: Global>(&mut self, global: T);
264    /// Updates the global state of the given type.
265    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
266    where
267        G: Global;
268}
269
270impl<C> BorrowAppContext for C
271where
272    C: BorrowMut<AppContext>,
273{
274    fn set_global<G: Global>(&mut self, global: G) {
275        self.borrow_mut().set_global(global)
276    }
277
278    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
279    where
280        G: Global,
281    {
282        let mut global = self.borrow_mut().lease_global::<G>();
283        let result = f(&mut global, self);
284        self.borrow_mut().end_global_lease(global);
285        result
286    }
287}
288
289/// A flatten equivalent for anyhow `Result`s.
290pub trait Flatten<T> {
291    /// Convert this type into a simple `Result<T>`.
292    fn flatten(self) -> Result<T>;
293}
294
295impl<T> Flatten<T> for Result<Result<T>> {
296    fn flatten(self) -> Result<T> {
297        self?
298    }
299}
300
301impl<T> Flatten<T> for Result<T> {
302    fn flatten(self) -> Result<T> {
303        self
304    }
305}
306
307/// A marker trait for types that can be stored in GPUI's global state.
308///
309/// Implement this on types you want to store in the context as a global.
310pub trait Global: 'static + Sized {
311    /// Access the global of the implementing type. Panics if a global for that type has not been assigned.
312    fn get(cx: &AppContext) -> &Self {
313        cx.global()
314    }
315
316    /// Updates the global of the implementing type with a closure. Unlike `global_mut`, this method provides
317    /// your closure with mutable access to the `AppContext` and the global simultaneously.
318    fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
319    where
320        C: BorrowAppContext,
321    {
322        cx.update_global(f)
323    }
324}