gpui-ce 0.3.0

A community fork of Zed's GPU-accelerated UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#![doc = include_str!("../docs/crate.md")]
#![warn(missing_docs)]
#![allow(clippy::type_complexity)] // Not useful, GPUI makes heavy use of callbacks
#![allow(clippy::collapsible_else_if)] // False positives in platform specific code
#![allow(unused_mut)] // False positives in platform specific code

extern crate self as gpui;
#[macro_use]
mod action;
mod animated;
mod app;

mod arena;
mod asset_cache;
mod assets;
mod bounds_tree;
mod color;
/// The default colors used by GPUI.
pub mod colors;
#[cfg(feature = "profiler")]
mod debug_overlay;
mod element;
mod elements;
mod executor;
mod platform_scheduler;
pub(crate) use platform_scheduler::PlatformScheduler;
/// Criterion measurements beyond wall time, for benchmarks built on GPUI.
#[cfg(feature = "bench-support")]
pub mod bench_metrics;
mod geometry;
mod gestures;
mod global;
mod input;
mod inspector;
mod interactive;
mod key_dispatch;
mod keymap;
mod lerp;
mod motion;
mod path_builder;
mod platform;
pub mod prelude;
/// Profiling utilities for task, frame, and thread performance tracking.
pub mod profiler;
#[cfg(any(
    test,
    target_os = "windows",
    target_os = "linux",
    target_family = "wasm",
    feature = "test-support",
    feature = "bench-support"
))]
pub mod queue;
/// A seeded, mutable element tree for benchmarks and tests of GPUI rendering.
#[cfg(any(test, feature = "bench-support"))]
pub mod randomized_element_tree;
mod resize;
mod scene;
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
mod seeds;
mod shared_uri;
mod spring;
mod style;
mod style_transitions;
mod styled;
mod subscription;
mod svg_renderer;
mod tab_stop;
mod taffy;
#[cfg(any(test, feature = "test-support"))]
pub mod test;
mod text_system;
mod transition;
mod util;
mod view;
mod window;

#[cfg(any(test, feature = "test-support"))]
pub use proptest;
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
pub use seeds::calculate_seeds;

pub mod _documentation;

/// Do not touch, here be dragons for use by gpui_macros and such.
#[doc(hidden)]
pub mod private {
    pub use anyhow;
    pub use inventory;
    pub use rand;
    pub use schemars;
    pub use serde;
    pub use serde_json;
}

mod seal {
    /// A mechanism for restricting implementations of a trait to only those in GPUI.
    /// See: <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
    pub trait Sealed {}
}

pub use accesskit;
pub use accesskit::Action as AccessibleAction;
pub use accesskit::{Orientation, Role, Toggled};
pub use action::*;
pub use animated::*;
pub use anyhow::Result;
pub use app::*;
pub(crate) use arena::*;
pub use asset_cache::*;
pub use assets::*;
pub use color::*;
pub use ctor::ctor;
#[cfg(feature = "profiler")]
pub use debug_overlay::*;
pub use element::*;
pub use elements::*;
pub use executor::*;
pub use geometry::*;
pub use gestures::*;
pub use global::*;
pub use gpui_macros::{
    AppContext, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement,
    Styled, VisualContext, bench, property_test, register_action, test,
};
pub use resize::*;
pub use spring::*;

/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].
///
/// It takes the same arguments as `criterion::criterion_group!`, so GPUI benchmark
/// files keep the shape of ordinary Criterion benchmarks.
///
/// The group measures with the `gpui::BenchMeasurement` configured by `BENCH_MEASUREMENT` (see
/// `BenchMeasurement::from_env`). By default Criterion analyzes wall time
/// while retired instructions, cycles, IPC, context switches, and the other
/// counters this machine supports are printed per iteration in the GPUI bench
/// report. `BENCH_MEASUREMENT=instructions` makes Criterion analyze
/// process-wide instructions instead, `foreground-instructions` the benchmark
/// thread's alone, and `wall-time` disables all counters. A
/// `config = ...` expression may set any other Criterion option; its
/// measurement is replaced. To measure with something else, call
/// `criterion::criterion_group!` directly with
/// `config = criterion::Criterion::default().with_measurement(gpui::BenchMeasurement::new(...))`.
///
/// [`gpui::bench`]: crate::bench
#[macro_export]
macro_rules! bench_group {
    (name = $name:ident; config = $config:expr; targets = $($target:path),+ $(,)?) => {
        criterion::criterion_group! {
            name = $name;
            config = ($config).with_measurement($crate::BenchMeasurement::from_env_or_exit());
            targets = $($target),+
        }
    };
    ($name:ident, $($target:path),+ $(,)?) => {
        $crate::bench_group! {
            name = $name;
            config = criterion::Criterion::default();
            targets = $($target),+
        }
    };
}

/// Defines the entry point for GPUI Criterion benchmark groups.
///
/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the
/// same shape as ordinary Criterion benchmarks. It also installs
/// `CountingAllocator` as the binary's global allocator, so reports include
/// heap allocations per iteration. It wraps the system allocator by default;
/// `allocator = Path;` wraps another unit-struct allocator instead, e.g. to
/// compare allocators, which pay the same small counting cost:
///
/// ```ignore
/// gpui::bench_main!(allocator = mimalloc::MiMalloc; benches);
/// ```
///
/// `allocator = none;` installs no global allocator, leaving Rust's default and
/// dropping the allocation metrics from reports.
#[macro_export]
macro_rules! bench_main {
    (allocator = none; $($groups:tt)*) => {
        criterion::criterion_main!($($groups)*);
    };
    (allocator = $allocator:path; $($groups:tt)*) => {
        #[global_allocator]
        static GPUI_BENCH_ALLOCATOR: $crate::CountingAllocator<$allocator> =
            $crate::CountingAllocator::new($allocator);

        criterion::criterion_main!($($groups)*);
    };
    ($($groups:tt)*) => {
        $crate::bench_main!(allocator = ::std::alloc::System; $($groups)*);
    };
}
pub use gpui_shared_string::*;
pub use gpui_util::arc_cow::ArcCow;
/// HTTP client abstraction for making requests.
pub mod http_client;
pub use input::*;
pub use inspector::*;
pub use interactive::*;
use key_dispatch::*;
pub use keymap::*;
pub use lerp::*;
pub use motion::*;
pub use path_builder::*;
pub use platform::*;
pub use profiler::*;
#[cfg(any(target_os = "windows", target_os = "linux", target_family = "wasm"))]
pub use queue::{PriorityQueueReceiver, PriorityQueueSender};
pub use refineable::*;
pub use scene::*;
pub use shared_uri::*;
use std::{any::Any, future::Future};
pub use style::*;
pub use style_transitions::*;
pub use styled::*;
pub use subscription::*;
pub use svg_renderer::*;
pub(crate) use tab_stop::*;
use taffy::TaffyLayoutEngine;
pub use taffy::{AvailableSpace, LayoutId};
#[cfg(any(test, feature = "test-support"))]
pub use test::*;
pub use text_system::*;
pub use transition::*;
pub use util::{FutureExt, TextRangeExt, Timeout};
pub use view::*;
pub use window::*;

#[cfg(not(target_family = "wasm"))]
pub use pollster::block_on;

/// Operations shared by GPUI's app, entity and async contexts.
///
/// Write a helper against this trait when it needs only entities, globals or the
/// app. Operations that need a window are on [`VisualContext`]. See
/// [contexts](crate::_documentation::concepts::contexts).
///
/// # Examples
///
/// ```
/// use gpui::{AppContext, Entity};
///
/// fn reset<C: AppContext>(count: &Entity<u64>, cx: &mut C) {
///     count.update(cx, |count, cx| {
///         *count = 0;
///         cx.notify();
///     });
/// }
/// # gpui::TestApp::new().update(|cx| {
/// #     let count = cx.new(|_| 5_u64);
/// #     reset(&count, cx);
/// #     assert_eq!(*count.read(cx), 0);
/// # });
/// ```
pub trait AppContext {
    /// Creates an entity from `build_entity`, and returns a handle to it.
    ///
    /// `build_entity` receives a [`Context`] for the new entity, so it can subscribe to
    /// other entities or start work of its own. The entity lives as long as a handle to
    /// it exists, or as long as it's stored with [`AppContext::insert_global_entity`].
    #[expect(
        clippy::wrong_self_convention,
        reason = "`App::new` is an ubiquitous function for creating entities"
    )]
    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;

    /// Reserves an entity slot, and returns a [`Reservation`] for it.
    ///
    /// The reservation's [`EntityId`] is known now, so you can refer to the entity before
    /// it exists. Create the entity later with [`AppContext::insert_entity`].
    ///
    /// # Examples
    ///
    /// ```
    /// use gpui::{AppContext, TestApp};
    ///
    /// let mut app = TestApp::new();
    /// app.update(|cx| {
    ///     let reservation = cx.reserve_entity::<u32>();
    ///     let id = reservation.entity_id();
    ///     let number = cx.insert_entity(reservation, |_| 7);
    ///     assert_eq!(number.entity_id(), id);
    ///     assert_eq!(*number.read(cx), 7);
    /// });
    /// ```
    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;

    /// Creates the entity for a [`Reservation`] from [`AppContext::reserve_entity`].
    ///
    /// The entity gets the reservation's [`EntityId`], and `build_entity` runs with a
    /// [`Context`] for it.
    fn insert_entity<T: 'static>(
        &mut self,
        reservation: Reservation<T>,
        build_entity: impl FnOnce(&mut Context<T>) -> T,
    ) -> Entity<T>;

    /// Runs `update` with the entity and a [`Context`] for it, and returns the result.
    ///
    /// Effects queued by `update`, such as notifications, run when the outermost update
    /// finishes.
    fn update_entity<T, R>(
        &mut self,
        handle: &Entity<T>,
        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
    ) -> R
    where
        T: 'static;

    /// Borrows the entity mutably, without a closure.
    ///
    /// The returned [`GpuiBorrow`] dereferences to the entity. Dropping it notifies
    /// observers of the entity. Prefer [`AppContext::update_entity`], which ends the
    /// borrow when its closure returns. Use this when you need to hold the borrow across
    /// several statements.
    ///
    /// # Panics
    ///
    /// Panics in [`AsyncApp`] and [`AsyncWindowContext`], which can't hold a borrow of
    /// the app across an `.await`. Call `update` there instead.
    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
    where
        T: 'static;

    /// Reads the entity with a shared borrow, and returns the result of `read`.
    ///
    /// `read` also receives the app, so it can read other state at the same time.
    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
    where
        T: 'static;

    /// Tells GPUI that the entity with `entity_id` changed. Its observers run and windows
    /// that show it redraw.
    ///
    /// Inside an entity's update, [`Context::notify`] is more convenient.
    fn notify(&mut self, entity_id: EntityId);

    /// Emits `event` from `entity`.
    ///
    /// Subscribers registered with [`Context::subscribe`] or [`AsyncApp::subscribe`]
    /// receive it when the current update finishes. Inside an entity's update,
    /// [`Context::emit`] is more convenient.
    fn emit<EntityType, EventType>(&mut self, entity: &Entity<EntityType>, event: EventType)
    where
        EntityType: EventEmitter<EventType>,
        EventType: 'static;

    /// Runs `f` with the window's root view, the window and the app, and returns the
    /// result.
    ///
    /// # Errors
    ///
    /// Returns an error if the window has closed. Async contexts also return an error when
    /// the app is already borrowed.
    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
    where
        F: FnOnce(AnyView, &mut Window, &mut App) -> T;

    /// Runs `f` with the window that most recently rendered the entity `entity_id`, and
    /// returns the result.
    ///
    /// Returns `None` if no window has rendered the entity, or if that window isn't
    /// available.
    fn with_window<R>(
        &mut self,
        entity_id: EntityId,
        f: impl FnOnce(&mut Window, &mut App) -> R,
    ) -> Option<R>;

    /// Reads the root view of `window` with the app, and returns the result.
    ///
    /// # Errors
    ///
    /// Returns an error if the window has closed.
    fn read_window<T, R>(
        &self,
        window: &WindowHandle<T>,
        read: impl FnOnce(Entity<T>, &App) -> R,
    ) -> Result<R>
    where
        T: 'static;

    /// Runs `future` on the background executor and returns a task for its result.
    ///
    /// Native builds use worker threads; single-threaded web builds use the browser's main
    /// thread. The future and its result must be `Send + 'static`. No app context is supplied,
    /// so return to a foreground task to update entities. Dropping the task cancels the future.
    /// See [`BackgroundExecutor::spawn`] and the [executor concept](crate::_documentation::concepts::executors).
    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
    where
        R: Send + 'static;

    /// Calls `callback` with the global of type `G` and the app, and returns the result.
    ///
    /// # Panics
    ///
    /// Panics if no global of type `G` has been set.
    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
    where
        G: Global;

    /// Keeps `entity` alive without a handle to it.
    ///
    /// The entity stays alive until the app is dropped, or until
    /// [`AppContext::remove_global_entity`] removes it and no other handle refers to it.
    fn insert_global_entity<T: 'static>(&mut self, entity: Entity<T>);

    /// Stops keeping `entity` alive. It's dropped once no other handle refers to it.
    fn remove_global_entity<T: 'static>(&mut self, entity: &Entity<T>);

    /// Returns the entities stored with [`AppContext::insert_global_entity`] whose type is
    /// `T`.
    fn global_entities<T: 'static>(&self) -> impl Iterator<Item = Entity<T>>;
}

/// A slot for an entity that doesn't exist yet.
///
/// Get one from [`AppContext::reserve_entity`], and pass it to
/// [`AppContext::insert_entity`] to create the entity.
pub struct Reservation<T>(pub(crate) Slot<T>);

impl<T: 'static> Reservation<T> {
    /// Returns the [`EntityId`] the entity will have once it's inserted.
    pub fn entity_id(&self) -> EntityId {
        self.0.entity_id()
    }
}

/// Operations that need a window.
///
/// Contexts that have a window implement this, including [`AsyncWindowContext`].
/// Import it along with [`AppContext`] from [`gpui::prelude`](crate::prelude).
pub trait VisualContext: AppContext {
    /// The return type of window operations.
    ///
    /// [`AsyncWindowContext`] uses [`Result`], because the window may have closed by the
    /// time the call runs.
    type Result<T>;

    /// Returns the handle of the window this context works in.
    fn window_handle(&self) -> AnyWindowHandle;

    /// Runs `update` with the entity, its window and a [`Context`] for the entity, and
    /// returns the result, wrapped in [`VisualContext::Result`](Self::Result).
    fn update_window_entity<T: 'static, R>(
        &mut self,
        entity: &Entity<T>,
        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
    ) -> Self::Result<R>;

    /// Creates an entity with access to the window.
    ///
    /// `build_entity` receives the window and a [`Context`] for the new entity.
    fn new_window_entity<T: 'static>(
        &mut self,
        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
    ) -> Self::Result<Entity<T>>;

    /// Replaces the root view of the window with the view that `build_view` creates, and
    /// returns a handle to the new view.
    fn replace_root_view<V>(
        &mut self,
        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
    ) -> Self::Result<Entity<V>>
    where
        V: 'static + Render;

    /// Moves keyboard focus to `entity`, using its [`Focusable::focus_handle`].
    fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
    where
        V: Focusable;
}

/// Declares that an entity type emits events of type `E`.
///
/// Implement it with an empty `impl`. Then emit events with [`Context::emit`], and
/// receive them with [`Context::subscribe`].
///
/// # Examples
///
/// ```
/// use gpui::{AppContext, Context, EventEmitter, TestApp};
///
/// struct Counter {
///     count: usize,
/// }
///
/// struct Incremented(usize);
///
/// impl EventEmitter<Incremented> for Counter {}
///
/// impl Counter {
///     fn add(&mut self, amount: usize, cx: &mut Context<Self>) {
///         self.count += amount;
///         cx.emit(Incremented(amount));
///         cx.notify();
///     }
/// }
///
/// let mut app = TestApp::new();
/// let (counter, total, _subscription) = app.update(|cx| {
///     let counter = cx.new(|_| Counter { count: 0 });
///     let total = cx.new(|_| 0_usize);
///     let total_for_subscriber = total.clone();
///     let subscription = cx.subscribe(&counter, move |_, event: &Incremented, cx| {
///         total_for_subscriber.update(cx, |total, _| *total += event.0);
///     });
///     (counter, total, subscription)
/// });
/// app.update(|cx| counter.update(cx, |counter, cx| counter.add(2, cx)));
/// app.read(|cx| assert_eq!(*total.read(cx), 2));
/// ```
pub trait EventEmitter<E: Any>: 'static {}

/// Helpers for changing globals from any context that can reach the [`App`].
///
/// Implemented for every type that implements `BorrowMut<App>`, including [`App`] and
/// [`Context`].
///
/// # Examples
///
/// ```
/// use gpui::{AppContext, BorrowAppContext, Global, TestApp};
///
/// struct Scale(f32);
///
/// impl Global for Scale {}
///
/// let mut app = TestApp::new();
/// app.update(|cx| {
///     cx.set_global(Scale(1.5));
///     cx.update_global(|scale: &mut Scale, _cx| scale.0 *= 2.0);
///     assert_eq!(cx.read_global(|scale: &Scale, _cx| scale.0), 3.0);
/// });
/// ```
pub trait BorrowAppContext {
    /// Sets the global of type `T` to `global`, replacing any previous value. Observers of
    /// the global are notified when the current update finishes.
    fn set_global<T: Global>(&mut self, global: T);
    /// Updates the global of type `G` with `f`, and returns the result of `f`.
    ///
    /// `f` also receives the context. While `f` runs, the global is taken out of the app,
    /// so reading it through the context panics. Change it only through the reference
    /// that `f` receives. Observers of the global are notified when the update ends.
    ///
    /// # Panics
    ///
    /// Panics if no global of type `G` has been set.
    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
    where
        G: Global;
    /// Like [`BorrowAppContext::update_global`], but first sets `G::default()` if no
    /// global of type `G` has been set.
    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
    where
        G: Global + Default;
}

impl<C> BorrowAppContext for C
where
    C: std::borrow::BorrowMut<App>,
{
    fn set_global<G: Global>(&mut self, global: G) {
        self.borrow_mut().set_global(global)
    }

    #[track_caller]
    fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
    where
        G: Global,
    {
        let mut global = self.borrow_mut().lease_global::<G>();
        let result = f(&mut global, self);
        self.borrow_mut().end_global_lease(global);
        result
    }

    fn update_default_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
    where
        G: Global + Default,
    {
        self.borrow_mut().default_global::<G>();
        self.update_global(f)
    }
}

/// Describes the GPU that GPUI renders with.
///
/// Get it from [`Window::gpu_specs`], which returns `None` when the platform doesn't
/// report it.
#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct GpuSpecs {
    /// Whether the GPU is a software renderer, such as `llvmpipe`, running on the CPU.
    pub is_software_emulated: bool,
    /// The name of the device, as reported by the graphics backend.
    pub device_name: String,
    /// The name of the driver, as reported by the graphics backend.
    pub driver_name: String,
    /// Further information about the driver, as reported by the graphics backend.
    pub driver_info: String,
}