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