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