Skip to main content

open_gpui/
gpui.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
4#![allow(clippy::collapsible_else_if)] // False positives in platform specific code
5#![allow(unused_mut)] // False positives in platform specific code
6
7extern crate self as open_gpui;
8#[doc(hidden)]
9pub static GPUI_MANIFEST_DIR: &'static str = env!("CARGO_MANIFEST_DIR");
10#[macro_use]
11mod action;
12mod app;
13
14mod arena;
15mod asset_cache;
16mod assets;
17mod bounds_tree;
18mod color;
19/// The default colors used by GPUI.
20pub mod colors;
21mod element;
22mod elements;
23mod executor;
24mod platform_scheduler;
25pub(crate) use platform_scheduler::PlatformScheduler;
26mod geometry;
27mod global;
28mod input;
29mod inspector;
30mod interactive;
31mod key_dispatch;
32mod keymap;
33mod path_builder;
34mod platform;
35pub mod prelude;
36/// Profiling utilities for task timing and thread performance tracking.
37pub mod profiler;
38#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
39#[expect(missing_docs)]
40pub mod queue;
41mod scene;
42mod shared_uri;
43mod style;
44mod styled;
45mod subscription;
46mod svg_renderer;
47mod tab_stop;
48mod taffy;
49#[cfg(any(test, feature = "test-support"))]
50pub mod test;
51mod text_system;
52mod util;
53mod view;
54mod window;
55
56#[cfg(any(test, feature = "test-support"))]
57pub use proptest;
58
59#[cfg(doc)]
60pub mod _accessibility;
61#[cfg(doc)]
62pub mod _ownership_and_data_flow;
63
64/// Do not touch, here be dragons for use by Open GPUI macros and such.
65#[doc(hidden)]
66pub mod private {
67    pub use anyhow;
68    pub use inventory;
69    pub use schemars;
70    pub use serde;
71    pub use serde_json;
72}
73
74mod seal {
75    /// A mechanism for restricting implementations of a trait to only those in GPUI.
76    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
77    pub trait Sealed {}
78}
79
80pub use accesskit;
81pub use accesskit::Action as AccessibleAction;
82pub use accesskit::{Orientation, Role, Toggled};
83pub use action::*;
84pub use anyhow::Result;
85pub use app::*;
86pub(crate) use arena::*;
87pub use asset_cache::*;
88pub use assets::*;
89pub use color::*;
90pub use ctor::ctor;
91pub use element::*;
92pub use elements::*;
93pub use executor::*;
94pub use geometry::*;
95pub use global::*;
96pub use open_gpui_macros::{
97    AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
98};
99
100/// Defines a Criterion benchmark group for benchmarks annotated with [`open_gpui::bench`].
101///
102/// This mirrors `criterion::criterion_group!` so GPUI benchmark files can keep the
103/// same shape as ordinary Criterion benchmarks.
104///
105/// [`open_gpui::bench`]: crate::bench
106#[macro_export]
107macro_rules! bench_group {
108    ($($tokens:tt)*) => {
109        criterion::criterion_group!($($tokens)*);
110    };
111}
112
113/// Defines the entry point for GPUI Criterion benchmark groups.
114///
115/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the
116/// same shape as ordinary Criterion benchmarks.
117#[macro_export]
118macro_rules! bench_main {
119    ($($tokens:tt)*) => {
120        criterion::criterion_main!($($tokens)*);
121    };
122}
123pub use input::*;
124pub use inspector::*;
125pub use interactive::*;
126use key_dispatch::*;
127pub use keymap::*;
128pub use open_gpui_core_util::arc_cow::ArcCow;
129pub use open_gpui_http_client as http_client;
130pub use open_gpui_refineable::*;
131pub use open_gpui_shared_string::*;
132pub use path_builder::*;
133pub use platform::*;
134pub use profiler::*;
135#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
136pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
137pub use scene::*;
138pub use shared_uri::*;
139use std::{any::Any, future::Future};
140pub use style::*;
141pub use styled::*;
142pub use subscription::*;
143pub use svg_renderer::*;
144pub(crate) use tab_stop::*;
145use taffy::TaffyLayoutEngine;
146pub use taffy::{AvailableSpace, LayoutId};
147#[cfg(any(test, feature = "test-support"))]
148pub use test::*;
149pub use text_system::*;
150pub use util::{FutureExt, Timeout};
151pub use view::*;
152pub use window::*;
153
154pub use pollster::block_on;
155
156/// The context trait, allows the different contexts in GPUI to be used
157/// interchangeably for certain operations.
158pub trait AppContext {
159    /// Create a new entity in the app context.
160    #[expect(
161        clippy::wrong_self_convention,
162        reason = "`App::new` is an ubiquitous function for creating entities"
163    )]
164    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
165
166    /// Reserve a slot for a entity to be inserted later.
167    /// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
168    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
169
170    /// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
171    ///
172    /// [`reserve_entity`]: Self::reserve_entity
173    fn insert_entity<T: 'static>(
174        &mut self,
175        reservation: Reservation<T>,
176        build_entity: impl FnOnce(&mut Context<T>) -> T,
177    ) -> Entity<T>;
178
179    /// Update a entity in the app context.
180    fn update_entity<T, R>(
181        &mut self,
182        handle: &Entity<T>,
183        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
184    ) -> R
185    where
186        T: 'static;
187
188    /// Update a entity in the app context.
189    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
190    where
191        T: 'static;
192
193    /// Read a entity from the app context.
194    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
195    where
196        T: 'static;
197
198    /// Update a window for the given handle.
199    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
200    where
201        F: FnOnce(AnyView, &mut Window, &mut App) -> T;
202
203    /// Run `f` against the entity's *current* window — the most recently
204    /// rendered window that referenced the entity. Returns `None` if the
205    /// entity has no current window or that window is unavailable. See
206    /// [`App::with_window`] for the underlying lookup.
207    fn with_window<R>(
208        &mut self,
209        entity_id: EntityId,
210        f: impl FnOnce(&mut Window, &mut App) -> R,
211    ) -> Option<R>;
212
213    /// Read a window off of the application context.
214    fn read_window<T, R>(
215        &self,
216        window: &WindowHandle<T>,
217        read: impl FnOnce(Entity<T>, &App) -> R,
218    ) -> Result<R>
219    where
220        T: 'static;
221
222    /// Spawn a future on a background thread
223    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
224    where
225        R: Send + 'static;
226
227    /// Read a global from this app context
228    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
229    where
230        G: Global;
231}
232
233/// Returned by [Context::reserve_entity] to later be passed to [Context::insert_entity].
234/// Allows you to obtain the [EntityId] for a entity before it is created.
235pub struct Reservation<T>(pub(crate) Slot<T>);
236
237impl<T: 'static> Reservation<T> {
238    /// Returns the [EntityId] that will be associated with the entity once it is inserted.
239    pub fn entity_id(&self) -> EntityId {
240        self.0.entity_id()
241    }
242}
243
244/// This trait is used for the different visual contexts in GPUI that
245/// require a window to be present.
246pub trait VisualContext: AppContext {
247    /// The result type for window operations.
248    type Result<T>;
249
250    /// Returns the handle of the window associated with this context.
251    fn window_handle(&self) -> AnyWindowHandle;
252
253    /// Update a view with the given callback
254    fn update_window_entity<T: 'static, R>(
255        &mut self,
256        entity: &Entity<T>,
257        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
258    ) -> Self::Result<R>;
259
260    /// Create a new entity, with access to `Window`.
261    fn new_window_entity<T: 'static>(
262        &mut self,
263        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
264    ) -> Self::Result<Entity<T>>;
265
266    /// Replace the root view of a window with a new view.
267    fn replace_root_view<V>(
268        &mut self,
269        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
270    ) -> Self::Result<Entity<V>>
271    where
272        V: 'static + Render;
273
274    /// Focus a entity in the window, if it implements the [`Focusable`] trait.
275    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
276    where
277        V: Focusable;
278}
279
280/// A trait for tying together the types of a GPUI entity and the events it can
281/// emit.
282pub trait EventEmitter<E: Any>: 'static {}
283
284/// A helper trait for auto-implementing certain methods on contexts that
285/// can be used interchangeably.
286pub trait BorrowAppContext {
287    /// Set a global value on the context.
288    fn set_global<T: Global>(&mut self, global: T);
289    /// Updates the global state of the given type.
290    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
291    where
292        G: Global;
293    /// Updates the global state of the given type, creating a default if it didn't exist before.
294    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
295    where
296        G: Global + Default;
297}
298
299impl<C> BorrowAppContext for C
300where
301    C: std::borrow::BorrowMut<App>,
302{
303    fn set_global<G: Global>(&mut self, global: G) {
304        self.borrow_mut().set_global(global)
305    }
306
307    #[track_caller]
308    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
309    where
310        G: Global,
311    {
312        let mut global = self.borrow_mut().lease_global::<G>();
313        let result = f(&mut global, self);
314        self.borrow_mut().end_global_lease(global);
315        result
316    }
317
318    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
319    where
320        G: Global + Default,
321    {
322        self.borrow_mut().default_global::<G>();
323        self.update_global(f)
324    }
325}
326
327/// Information about the GPU GPUI is running on.
328#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
329pub struct GpuSpecs {
330    /// Whether the GPU is really a fake (like `llvmpipe`) running on the CPU.
331    pub is_software_emulated: bool,
332    /// The name of the device, as reported by Vulkan.
333    pub device_name: String,
334    /// The name of the driver, as reported by Vulkan.
335    pub driver_name: String,
336    /// Further information about the driver, as reported by Vulkan.
337    pub driver_info: String,
338}