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