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