Skip to main content

gpui/
gpui.rs

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