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