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