Vendor gpui-pre 0.3.8 unmodified (crates.io source)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
ba5c0798cb
commit
48a66ca6c1
162 files changed
+104826
-2
No files matched your search
+557
@@ -0,0 +1,557 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
|
||||
Entity, EntityId, EventEmitter, Focusable, ForegroundExecutor, Global, GpuiBorrow,
|
||||
PromptButton, PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext,
|
||||
Window, WindowHandle,
|
||||
};
|
||||
use anyhow::{Context as _, bail};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use futures::channel::oneshot;
|
||||
use futures::future::FutureExt;
|
||||
use std::{future::Future, rc::Weak};
|
||||
|
||||
use super::{Context, WeakEntity};
|
||||
|
||||
/// An async-friendly version of [App] with a static lifetime so it can be held across `await` points in async code.
|
||||
/// You're provided with an instance when calling [App::spawn], and you can also create one with [App::to_async].
|
||||
///
|
||||
/// Internally, this holds a weak reference to an `App`. Methods will panic if the app has been dropped,
|
||||
/// but this should not happen in practice when using foreground tasks spawned via `cx.spawn()`,
|
||||
/// as the executor checks if the app is alive before running each task.
|
||||
#[derive(Clone)]
|
||||
pub struct AsyncApp {
|
||||
pub(crate) app: Weak<AppCell>,
|
||||
pub(crate) background_executor: BackgroundExecutor,
|
||||
pub(crate) foreground_executor: ForegroundExecutor,
|
||||
}
|
||||
|
||||
impl AsyncApp {
|
||||
fn app(&self) -> std::rc::Rc<AppCell> {
|
||||
self.app
|
||||
.upgrade()
|
||||
.expect("app was released before async operation completed")
|
||||
}
|
||||
}
|
||||
|
||||
impl AppContext for AsyncApp {
|
||||
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.reserve_entity()
|
||||
}
|
||||
|
||||
fn insert_entity<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Entity<T> {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> R {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
panic!("Cannot as_mut with an async context. Try calling update() first")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, callback: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app();
|
||||
let lock = app.borrow();
|
||||
lock.read_entity(handle, callback)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let mut lock = app.try_borrow_mut()?;
|
||||
if lock.quitting {
|
||||
bail!("app is quitting");
|
||||
}
|
||||
lock.update_window(window, f)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn with_window<R>(
|
||||
&mut self,
|
||||
entity_id: EntityId,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> R,
|
||||
) -> Option<R> {
|
||||
let app = self.app.upgrade()?;
|
||||
let mut lock = app.try_borrow_mut().ok()?;
|
||||
if lock.quitting {
|
||||
return None;
|
||||
}
|
||||
lock.with_window(entity_id, f)
|
||||
}
|
||||
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let lock = app.borrow();
|
||||
if lock.quitting {
|
||||
bail!("app is quitting");
|
||||
}
|
||||
lock.read_window(window, read)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.update(|this| this.read_global(callback))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncApp {
|
||||
/// Schedules all windows in the application to be redrawn.
|
||||
pub fn refresh(&self) {
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
// A direct call would leave the refresh effect queued, which cannot wake
|
||||
// a platform render loop that has already parked.
|
||||
lock.update(|cx| cx.refresh_windows());
|
||||
}
|
||||
|
||||
/// Get an executor which can be used to spawn futures in the background.
|
||||
pub fn background_executor(&self) -> &BackgroundExecutor {
|
||||
&self.background_executor
|
||||
}
|
||||
|
||||
/// Whether this app runs on the deterministic test scheduler. See
|
||||
/// [`BackgroundExecutor::is_test`].
|
||||
pub fn is_test(&self) -> bool {
|
||||
self.background_executor.is_test()
|
||||
}
|
||||
|
||||
/// Get an executor which can be used to spawn futures in the foreground.
|
||||
pub fn foreground_executor(&self) -> &ForegroundExecutor {
|
||||
&self.foreground_executor
|
||||
}
|
||||
|
||||
/// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
|
||||
#[inline(always)]
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.update(f)
|
||||
}
|
||||
|
||||
/// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
|
||||
/// The callback is provided a handle to the emitting entity and a reference to the emitted event.
|
||||
pub fn subscribe<T, Event>(
|
||||
&mut self,
|
||||
entity: &Entity<T>,
|
||||
on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static + EventEmitter<Event>,
|
||||
Event: 'static,
|
||||
{
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.subscribe(entity, on_event)
|
||||
}
|
||||
|
||||
/// Open a window with the given options based on the root view returned by the given function.
|
||||
pub fn open_window<V>(
|
||||
&self,
|
||||
options: crate::WindowOptions,
|
||||
build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> Result<WindowHandle<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
if lock.quitting {
|
||||
bail!("app is quitting");
|
||||
}
|
||||
lock.open_window(options, build_root_view)
|
||||
}
|
||||
|
||||
/// Schedule a future to be polled in the foreground.
|
||||
#[track_caller]
|
||||
#[inline(always)]
|
||||
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
|
||||
where
|
||||
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
|
||||
R: 'static,
|
||||
{
|
||||
let mut cx = self.clone();
|
||||
self.foreground_executor
|
||||
.spawn(async move { f(&mut cx).await }.boxed_local())
|
||||
}
|
||||
|
||||
/// Determine whether global state of the specified type has been assigned.
|
||||
pub fn has_global<G: Global>(&self) -> bool {
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
app.has_global::<G>()
|
||||
}
|
||||
|
||||
/// Reads the global state of the specified type, passing it to the given callback.
|
||||
///
|
||||
/// Panics if no global state of the specified type has been assigned.
|
||||
#[inline(always)]
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
read(app.global(), &app)
|
||||
}
|
||||
|
||||
/// Reads the global state of the specified type, passing it to the given callback.
|
||||
///
|
||||
/// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
|
||||
pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
if app.quitting {
|
||||
return None;
|
||||
}
|
||||
Some(read(app.try_global()?, &app))
|
||||
}
|
||||
|
||||
/// Reads the global state of the specified type, passing it to the given callback.
|
||||
/// A default value is assigned if a global of this type has not yet been assigned.
|
||||
pub fn read_default_global<G: Global + Default, R>(
|
||||
&self,
|
||||
read: impl FnOnce(&G, &App) -> R,
|
||||
) -> R {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.update(|cx| {
|
||||
cx.default_global::<G>();
|
||||
});
|
||||
read(app.global(), &app)
|
||||
}
|
||||
|
||||
/// A convenience method for [`App::update_global`](BorrowAppContext::update_global)
|
||||
/// for updating the global state of the specified type.
|
||||
pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.update(|cx| cx.update_global(update))
|
||||
}
|
||||
|
||||
/// Run something using this entity and cx, when the returned struct is dropped
|
||||
pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
|
||||
&self,
|
||||
entity: &WeakEntity<T>,
|
||||
f: Callback,
|
||||
) -> gpui_util::Deferred<impl FnOnce() + use<T, Callback>> {
|
||||
let entity = entity.clone();
|
||||
let mut cx = self.clone();
|
||||
gpui_util::defer(move || {
|
||||
entity.update(&mut cx, f).ok();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A cloneable, owned handle to the application context,
|
||||
/// composed with the window associated with the current task.
|
||||
#[derive(Clone, Deref, DerefMut)]
|
||||
pub struct AsyncWindowContext {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
app: AsyncApp,
|
||||
window: AnyWindowHandle,
|
||||
}
|
||||
|
||||
impl AsyncWindowContext {
|
||||
pub(crate) fn new_context(app: AsyncApp, window: AnyWindowHandle) -> Self {
|
||||
Self { app, window }
|
||||
}
|
||||
|
||||
/// Get the handle of the window this context is associated with.
|
||||
pub fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
}
|
||||
|
||||
/// A convenience method for [`App::update_window`].
|
||||
#[inline(always)]
|
||||
pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
|
||||
self.app
|
||||
.update_window(self.window, |_, window, cx| update(window, cx))
|
||||
}
|
||||
|
||||
/// A convenience method for [`App::update_window`].
|
||||
#[inline(always)]
|
||||
pub fn update_root<R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
|
||||
) -> Result<R> {
|
||||
self.app.update_window(self.window, update)
|
||||
}
|
||||
|
||||
/// A convenience method for [`Window::on_next_frame`].
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
|
||||
self.app
|
||||
.update_window(self.window, |_, window, _| window.on_next_frame(f))
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// A convenience method for [`App::global`].
|
||||
pub fn read_global<G: Global, R>(
|
||||
&mut self,
|
||||
read: impl FnOnce(&G, &Window, &App) -> R,
|
||||
) -> Result<R> {
|
||||
self.app
|
||||
.update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
|
||||
}
|
||||
|
||||
/// A convenience method for [`App::update_global`](BorrowAppContext::update_global).
|
||||
/// for updating the global state of the specified type.
|
||||
pub fn update_global<G, R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
cx.update_global(|global, cx| update(global, window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// Schedule a future to be executed on the main thread. This is used for collecting
|
||||
/// the results of background tasks and updating the UI.
|
||||
#[track_caller]
|
||||
#[inline(always)]
|
||||
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
|
||||
where
|
||||
AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
|
||||
R: 'static,
|
||||
{
|
||||
let mut cx = self.clone();
|
||||
self.foreground_executor
|
||||
.spawn(async move { f(&mut cx).await }.boxed_local())
|
||||
}
|
||||
|
||||
/// Present a platform dialog.
|
||||
/// The provided message will be presented, along with buttons for each answer.
|
||||
/// When a button is clicked, the returned Receiver will receive the index of the clicked button.
|
||||
pub fn prompt<T>(
|
||||
&mut self,
|
||||
level: PromptLevel,
|
||||
message: &str,
|
||||
detail: Option<&str>,
|
||||
answers: &[T],
|
||||
) -> oneshot::Receiver<usize>
|
||||
where
|
||||
T: Clone + Into<PromptButton>,
|
||||
{
|
||||
self.app
|
||||
.update_window(self.window, |_, window, cx| {
|
||||
window.prompt(level, message, detail, answers, cx)
|
||||
})
|
||||
.unwrap_or_else(|_| oneshot::channel().1)
|
||||
}
|
||||
}
|
||||
|
||||
impl AppContext for AsyncWindowContext {
|
||||
fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let mut build_entity = Some(build_entity);
|
||||
match self.app.update_window(self.window, |_, _, cx| {
|
||||
cx.new(
|
||||
build_entity
|
||||
.take()
|
||||
.expect("build_entity is taken exactly once"),
|
||||
)
|
||||
}) {
|
||||
Ok(entity) => entity,
|
||||
Err(_) => self.app.new(
|
||||
build_entity
|
||||
.take()
|
||||
.expect("update_window returned Err without invoking the closure"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
|
||||
self.app.reserve_entity()
|
||||
}
|
||||
|
||||
fn insert_entity<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Entity<T> {
|
||||
let mut args = Some((reservation, build_entity));
|
||||
match self.app.update_window(self.window, |_, _, cx| {
|
||||
let (reservation, build_entity) = args.take().expect("args are taken exactly once");
|
||||
cx.insert_entity(reservation, build_entity)
|
||||
}) {
|
||||
Ok(entity) => entity,
|
||||
Err(_) => {
|
||||
let (reservation, build_entity) = args
|
||||
.take()
|
||||
.expect("update_window returned Err without invoking the closure");
|
||||
self.app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> R {
|
||||
self.app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
panic!("Cannot use as_mut() from an async context, call `update`")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.app.read_entity(handle, read)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
self.app.update_window(window, update)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn with_window<R>(
|
||||
&mut self,
|
||||
entity_id: EntityId,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> R,
|
||||
) -> Option<R> {
|
||||
self.app.with_window(entity_id, f)
|
||||
}
|
||||
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.app.read_window(window, read)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.app.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
self.app.read_global(callback)
|
||||
}
|
||||
}
|
||||
|
||||
impl VisualContext for AsyncWindowContext {
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
}
|
||||
|
||||
fn new_window_entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
|
||||
) -> Result<Entity<T>> {
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
cx.new(|cx| build_entity(window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
fn update_window_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
view: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> Result<R> {
|
||||
let view = view.clone();
|
||||
self.app
|
||||
.with_window(view.entity_id(), |window, app| {
|
||||
view.update(app, |entity, cx| update(entity, window, cx))
|
||||
})
|
||||
.context("entity has no current window")
|
||||
}
|
||||
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
window.replace_root(cx, build_view)
|
||||
})
|
||||
}
|
||||
|
||||
fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
|
||||
where
|
||||
V: Focusable,
|
||||
{
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
view.read(cx).focus_handle(cx).focus(window, cx);
|
||||
})
|
||||
}
|
||||
}
|
||||
+1596
File diff suppressed because it is too large.
Load diff
Vendored
+959
@@ -0,0 +1,959 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,
|
||||
FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
|
||||
SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
|
||||
WindowVisibility,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use futures::FutureExt;
|
||||
use gpui_util::Deferred;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
borrow::{Borrow, BorrowMut},
|
||||
future::Future,
|
||||
ops,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::{App, AsyncWindowContext, Entity, KeystrokeEvent};
|
||||
|
||||
/// The app context, with specialized behavior for the given entity.
|
||||
pub struct Context<'a, T> {
|
||||
app: &'a mut App,
|
||||
entity_state: WeakEntity<T>,
|
||||
}
|
||||
|
||||
impl<'a, T> ops::Deref for Context<'a, T> {
|
||||
type Target = App;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> ops::DerefMut for Context<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'static> Context<'a, T> {
|
||||
pub(crate) fn new_context(app: &'a mut App, entity_state: WeakEntity<T>) -> Self {
|
||||
Self { app, entity_state }
|
||||
}
|
||||
|
||||
/// The entity id of the entity backing this context.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.entity_state.entity_id
|
||||
}
|
||||
|
||||
/// Returns a handle to the entity belonging to this context.
|
||||
pub fn entity(&self) -> Entity<T> {
|
||||
self.weak_entity()
|
||||
.upgrade()
|
||||
.expect("The entity must be alive if we have a entity context")
|
||||
}
|
||||
|
||||
/// Returns a weak handle to the entity belonging to this context.
|
||||
pub fn weak_entity(&self) -> WeakEntity<T> {
|
||||
self.entity_state.clone()
|
||||
}
|
||||
|
||||
/// Arranges for the given function to be called whenever [`Context::notify`] is
|
||||
/// called with the given entity.
|
||||
pub fn observe<W>(
|
||||
&mut self,
|
||||
entity: &Entity<W>,
|
||||
mut on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
W: 'static,
|
||||
{
|
||||
let observer = self.weak_entity();
|
||||
self.app.observe_internal(entity, move |entity, cx| {
|
||||
invoke_observer(&observer, entity, cx, &mut on_notify)
|
||||
})
|
||||
}
|
||||
|
||||
/// Observe changes to ourselves
|
||||
pub fn observe_self(
|
||||
&mut self,
|
||||
mut on_event: impl FnMut(&mut T, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let this = self.entity();
|
||||
self.app.observe(&this, move |this, cx| {
|
||||
this.update(cx, |this, cx| on_event(this, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// Subscribe to an event type from another entity
|
||||
pub fn subscribe<T2, Evt>(
|
||||
&mut self,
|
||||
entity: &Entity<T2>,
|
||||
mut on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
T2: 'static + EventEmitter<Evt>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let subscriber = self.weak_entity();
|
||||
self.app
|
||||
.subscribe_internal(entity, move |entity, event, cx| {
|
||||
invoke_subscriber(&subscriber, entity, event, cx, &mut on_event)
|
||||
})
|
||||
}
|
||||
|
||||
/// Subscribe to an event type from ourself
|
||||
pub fn subscribe_self<Evt>(
|
||||
&mut self,
|
||||
mut on_event: impl FnMut(&mut T, &Evt, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static + EventEmitter<Evt>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let this = self.entity();
|
||||
self.app.subscribe(&this, move |this, evt, cx| {
|
||||
this.update(cx, |this, cx| on_event(this, evt, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when GPUI releases this entity.
|
||||
pub fn on_release(&self, on_release: impl FnOnce(&mut T, &mut App) + 'static) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let (subscription, activate) = self.app.release_listeners.insert(
|
||||
self.entity_state.entity_id,
|
||||
Box::new(move |this, cx| {
|
||||
let this = this.downcast_mut().expect("invalid entity type");
|
||||
on_release(this, cx);
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be run on the release of another entity
|
||||
pub fn observe_release<T2>(
|
||||
&self,
|
||||
entity: &Entity<T2>,
|
||||
on_release: impl FnOnce(&mut T, &mut T2, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any,
|
||||
T2: 'static,
|
||||
{
|
||||
let entity_id = entity.entity_id();
|
||||
let this = self.weak_entity();
|
||||
let (subscription, activate) = self.app.release_listeners.insert(
|
||||
entity_id,
|
||||
Box::new(move |entity, cx| {
|
||||
let entity = entity.downcast_mut().expect("invalid entity type");
|
||||
if let Some(this) = this.upgrade() {
|
||||
this.update(cx, |this, cx| on_release(this, entity, cx));
|
||||
}
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to for updates to the given global
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut T, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let handle = self.weak_entity();
|
||||
let (subscription, activate) = self.global_observers.insert(
|
||||
TypeId::of::<G>(),
|
||||
Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
|
||||
);
|
||||
self.defer(move |_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the application is about to restart.
|
||||
pub fn on_app_restart(
|
||||
&self,
|
||||
mut on_restart: impl FnMut(&mut T, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let handle = self.weak_entity();
|
||||
self.app.on_app_restart(move |cx| {
|
||||
handle.update(cx, |entity, cx| on_restart(entity, cx)).ok();
|
||||
})
|
||||
}
|
||||
|
||||
/// Arrange for the given function to be invoked whenever the application is quit.
|
||||
/// The future returned from this callback will be polled for up to [crate::SHUTDOWN_TIMEOUT] until the app fully quits.
|
||||
pub fn on_app_quit<Fut>(
|
||||
&self,
|
||||
mut on_quit: impl FnMut(&mut T, &mut Context<T>) -> Fut + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Fut: 'static + Future<Output = ()>,
|
||||
T: 'static,
|
||||
{
|
||||
let handle = self.weak_entity();
|
||||
self.app.on_app_quit(move |cx| {
|
||||
let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
|
||||
async move {
|
||||
if let Some(future) = future {
|
||||
future.await;
|
||||
}
|
||||
}
|
||||
.boxed_local()
|
||||
})
|
||||
}
|
||||
|
||||
/// Tell GPUI that this entity has changed and observers of it should be notified.
|
||||
pub fn notify(&mut self) {
|
||||
self.app.notify(self.entity_state.entity_id);
|
||||
}
|
||||
|
||||
/// Spawn the future returned by the given function.
|
||||
/// The function is provided a weak handle to the entity owned by this context and a context that can be held across await points.
|
||||
/// The returned task must be held or detached.
|
||||
#[track_caller]
|
||||
#[inline(always)]
|
||||
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
|
||||
where
|
||||
T: 'static,
|
||||
AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncApp) -> R + 'static,
|
||||
R: 'static,
|
||||
{
|
||||
let this = self.weak_entity();
|
||||
self.app.spawn(async move |cx| f(this, cx).await)
|
||||
}
|
||||
|
||||
/// Convenience method for accessing view state in an event callback.
|
||||
///
|
||||
/// Many GPUI callbacks take the form of `Fn(&E, &mut Window, &mut App)`,
|
||||
/// but it's often useful to be able to access view state in these
|
||||
/// callbacks. This method provides a convenient way to do so.
|
||||
#[inline(always)]
|
||||
pub fn listener<E: ?Sized>(
|
||||
&self,
|
||||
listener: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
|
||||
let view = self.entity().downgrade();
|
||||
move |event: &E, window: &mut Window, cx: &mut App| {
|
||||
invoke_listener(&view, window, cx, &|view, window, cx| {
|
||||
listener(view, event, window, cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience method for producing view state in a closure.
|
||||
/// See `listener` for more details.
|
||||
pub fn processor<E, R>(
|
||||
&self,
|
||||
f: impl Fn(&mut T, E, &mut Window, &mut Context<T>) -> R + 'static,
|
||||
) -> impl Fn(E, &mut Window, &mut App) -> R + 'static {
|
||||
let view = self.entity();
|
||||
move |e: E, window: &mut Window, cx: &mut App| {
|
||||
view.update(cx, |view, cx| f(view, e, window, cx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Run something using this entity and cx, when the returned struct is dropped
|
||||
pub fn on_drop(
|
||||
&self,
|
||||
f: impl FnOnce(&mut T, &mut Context<T>) + 'static,
|
||||
) -> Deferred<impl FnOnce()> {
|
||||
let this = self.weak_entity();
|
||||
let mut cx = self.to_async();
|
||||
gpui_util::defer(move || {
|
||||
this.update(&mut cx, f).ok();
|
||||
})
|
||||
}
|
||||
|
||||
/// Focus the given view in the given window. View type is required to implement Focusable.
|
||||
pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
|
||||
window.focus(&view.focus_handle(self), self);
|
||||
}
|
||||
|
||||
/// Sets a given callback to be run on the next frame.
|
||||
pub fn on_next_frame(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) where
|
||||
T: 'static,
|
||||
{
|
||||
let view = self.entity();
|
||||
window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
|
||||
}
|
||||
|
||||
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
|
||||
/// that are currently on the stack to be returned to the app.
|
||||
pub fn defer_in(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) {
|
||||
let view = self.weak_entity();
|
||||
let entity_id = self.entity_id();
|
||||
self.ensure_window(entity_id, window.handle.id);
|
||||
self.app.defer(move |cx| {
|
||||
cx.with_window(entity_id, |window, cx| {
|
||||
view.update(cx, |view, cx| f(view, window, cx)).ok();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Observe another entity for changes to its state, as tracked by [`Context::notify`].
|
||||
pub fn observe_in<V2>(
|
||||
&mut self,
|
||||
observed: &Entity<V2>,
|
||||
window: &mut Window,
|
||||
mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
V2: 'static,
|
||||
T: 'static,
|
||||
{
|
||||
let observed_id = observed.entity_id();
|
||||
let observed = observed.downgrade();
|
||||
let observer = self.weak_entity();
|
||||
let observer_id = self.entity_id();
|
||||
self.ensure_window(observer_id, window.handle.id);
|
||||
self.new_observer(
|
||||
observed_id,
|
||||
Box::new(move |cx| invoke_observer_in(&observer, &observed, cx, &mut on_notify)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Subscribe to events emitted by another entity.
|
||||
/// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
|
||||
/// The callback will be invoked with a reference to the current view, a handle to the emitting `Entity`, the event, a mutable reference to the `Window`, and the context for the entity.
|
||||
pub fn subscribe_in<Emitter, Evt>(
|
||||
&mut self,
|
||||
emitter: &Entity<Emitter>,
|
||||
window: &Window,
|
||||
mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Emitter: EventEmitter<Evt>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let emitter = emitter.downgrade();
|
||||
let subscriber = self.weak_entity();
|
||||
let subscriber_id = self.entity_id();
|
||||
self.ensure_window(subscriber_id, window.handle.id);
|
||||
self.new_subscription(
|
||||
emitter.entity_id(),
|
||||
(
|
||||
TypeId::of::<Evt>(),
|
||||
Box::new(move |event, cx| {
|
||||
invoke_subscriber_in(&subscriber, &emitter, event, cx, &mut on_event)
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the view is released.
|
||||
///
|
||||
/// The callback receives a handle to the view's window. This handle may be
|
||||
/// invalid, if the window was closed before the view was released.
|
||||
pub fn on_release_in(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
|
||||
) -> Subscription {
|
||||
let entity = self.entity();
|
||||
self.app.observe_release_in(&entity, window, on_release)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given Entity is released.
|
||||
pub fn observe_release_in<T2>(
|
||||
&self,
|
||||
observed: &Entity<T2>,
|
||||
window: &Window,
|
||||
mut on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
T2: 'static,
|
||||
{
|
||||
let observer = self.weak_entity();
|
||||
self.app
|
||||
.observe_release_in(observed, window, move |observed, window, cx| {
|
||||
observer
|
||||
.update(cx, |observer, cx| {
|
||||
on_release(observer, observed, window, cx)
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window is resized.
|
||||
pub fn observe_window_bounds(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.bounds_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window is activated or deactivated.
|
||||
pub fn observe_window_activation(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.activation_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Registers a callback to be invoked when the window's visibility changes
|
||||
/// (see [`WindowVisibility`]).
|
||||
pub fn observe_window_visibility(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.visibility_observers.insert(
|
||||
(),
|
||||
Box::new(move |visibility, window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, visibility, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Registers a callback to be invoked when the window appearance changes.
|
||||
pub fn observe_window_appearance(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.appearance_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Registers a callback to be invoked when the window button layout changes.
|
||||
pub fn observe_button_layout_changed(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.button_layout_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Registers a callback for [`App::observe_keystrokes`] that updates this entity.
|
||||
pub fn observe_keystrokes(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
fn inner(
|
||||
keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
|
||||
handler: KeystrokeObserver,
|
||||
) -> Subscription {
|
||||
let (subscription, activate) = keystroke_observers.insert((), handler);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
let view = self.weak_entity();
|
||||
inner(
|
||||
&self.keystroke_observers,
|
||||
Box::new(move |event, window, cx| {
|
||||
if let Some(view) = view.upgrade() {
|
||||
view.update(cx, |view, cx| f(view, event, window, cx));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window's pending input changes.
|
||||
pub fn observe_pending_input(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.pending_input_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle receives focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.previous_focus_path.last() != Some(&focus_id)
|
||||
&& event.current_focus_path.last() == Some(&focus_id)
|
||||
{
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle or one of its descendants receives focus.
|
||||
/// This does not fire if the given focus handle - or one of its descendants - was previously focused.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_in(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.is_focus_in(focus_id) {
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle loses focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_blur(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.previous_focus_path.last() == Some(&focus_id)
|
||||
&& event.current_focus_path.last() != Some(&focus_id)
|
||||
{
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when nothing in the window has focus.
|
||||
/// This typically happens when the node that was focused is removed from the tree,
|
||||
/// and this callback lets you chose a default place to restore the users focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_lost(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = window.focus_lost_listeners.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| listener(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle or one of its descendants loses focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_out(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_entity();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if let Some(blurred_id) = event.previous_focus_path.last().copied()
|
||||
&& event.is_focus_out(focus_id)
|
||||
{
|
||||
let event = FocusOutEvent {
|
||||
blurred: WeakFocusHandle {
|
||||
id: blurred_id,
|
||||
handles: Arc::downgrade(&cx.focus_handles),
|
||||
},
|
||||
};
|
||||
listener(view, event, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Schedule a future to be run asynchronously.
|
||||
/// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
|
||||
/// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
|
||||
/// The returned future will be polled on the main thread.
|
||||
#[track_caller]
|
||||
#[inline(always)]
|
||||
pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
|
||||
{
|
||||
let view = self.weak_entity();
|
||||
window.spawn(self, async move |cx| f(view, cx).await)
|
||||
}
|
||||
|
||||
/// Schedule a future to be run asynchronously with the given priority.
|
||||
/// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
|
||||
/// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
|
||||
/// The returned future will be polled on the main thread.
|
||||
#[track_caller]
|
||||
#[inline(always)]
|
||||
pub fn spawn_in_with_priority<AsyncFn, R>(
|
||||
&self,
|
||||
priority: Priority,
|
||||
window: &Window,
|
||||
f: AsyncFn,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
|
||||
{
|
||||
let view = self.weak_entity();
|
||||
window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given global state changes.
|
||||
pub fn observe_global_in<G: Global>(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = window.handle;
|
||||
let view = self.weak_entity();
|
||||
let (subscription, activate) = self.global_observers.insert(
|
||||
TypeId::of::<G>(),
|
||||
Box::new(move |cx| {
|
||||
// If the entity has been dropped, remove this observer.
|
||||
if view.upgrade().is_none() {
|
||||
return false;
|
||||
}
|
||||
// If the window is unavailable (e.g. temporarily taken during a
|
||||
// nested update, or already closed), skip this notification but
|
||||
// keep the observer alive so it can fire on future changes.
|
||||
let Ok(entity_alive) = window_handle.update(cx, |_, window, cx| {
|
||||
view.update(cx, |view, cx| f(view, window, cx)).is_ok()
|
||||
}) else {
|
||||
return true;
|
||||
};
|
||||
entity_alive
|
||||
}),
|
||||
);
|
||||
self.defer(move |_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given Action type is dispatched to the window.
|
||||
pub fn on_action(
|
||||
&mut self,
|
||||
action_type: TypeId,
|
||||
window: &mut Window,
|
||||
listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
|
||||
) {
|
||||
let handle = self.weak_entity();
|
||||
window.on_action(action_type, move |action, phase, window, cx| {
|
||||
handle
|
||||
.update(cx, |view, cx| {
|
||||
listener(view, action, phase, window, cx);
|
||||
})
|
||||
.ok();
|
||||
});
|
||||
}
|
||||
|
||||
/// Move focus to the current view, assuming it implements [`Focusable`].
|
||||
pub fn focus_self(&mut self, window: &mut Window)
|
||||
where
|
||||
T: Focusable,
|
||||
{
|
||||
let view = self.entity();
|
||||
window.defer(self, move |window, cx| {
|
||||
view.read(cx).focus_handle(cx).focus(window, cx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Context<'_, T> {
|
||||
/// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
|
||||
pub fn emit<Evt>(&mut self, event: Evt)
|
||||
where
|
||||
T: EventEmitter<Evt>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let event = self
|
||||
.event_arena
|
||||
.alloc(|| event)
|
||||
.map(|it| it as &mut dyn Any);
|
||||
self.app.pending_effects.push_back(Effect::Emit {
|
||||
emitter: self.entity_state.entity_id,
|
||||
event_type: TypeId::of::<Evt>(),
|
||||
event,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AppContext for Context<'_, T> {
|
||||
#[inline]
|
||||
fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
|
||||
self.app.new(build_entity)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn reserve_entity<U: 'static>(&mut self) -> Reservation<U> {
|
||||
self.app.reserve_entity()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn insert_entity<U: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<U>,
|
||||
build_entity: impl FnOnce(&mut Context<U>) -> U,
|
||||
) -> Entity<U> {
|
||||
self.app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn update_entity<U: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Entity<U>,
|
||||
update: impl FnOnce(&mut U, &mut Context<U>) -> R,
|
||||
) -> R {
|
||||
self.app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> super::GpuiBorrow<'a, E>
|
||||
where
|
||||
E: 'static,
|
||||
{
|
||||
self.app.as_mut(handle)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_entity<U, R>(&self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R) -> R
|
||||
where
|
||||
U: 'static,
|
||||
{
|
||||
self.app.read_entity(handle, read)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> R,
|
||||
{
|
||||
self.app.update_window(window, update)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_window<R>(
|
||||
&mut self,
|
||||
entity_id: EntityId,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> R,
|
||||
) -> Option<R> {
|
||||
self.app.with_window(entity_id, f)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_window<U, R>(
|
||||
&self,
|
||||
window: &WindowHandle<U>,
|
||||
read: impl FnOnce(Entity<U>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
U: 'static,
|
||||
{
|
||||
self.app.read_window(window, read)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.app.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
self.app.read_global(callback)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Borrow<App> for Context<'_, T> {
|
||||
fn borrow(&self) -> &App {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> BorrowMut<App> for Context<'_, T> {
|
||||
fn borrow_mut(&mut self) -> &mut App {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn invoke_observer<T: 'static, W: 'static>(
|
||||
observer: &WeakEntity<T>,
|
||||
observed: Entity<W>,
|
||||
cx: &mut App,
|
||||
on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Context<T>),
|
||||
) -> bool {
|
||||
if let Some(observer) = observer.upgrade() {
|
||||
observer.update(cx, |observer, cx| on_notify(observer, observed, cx));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn invoke_subscriber<T: 'static, Emitter: 'static, Event: 'static>(
|
||||
subscriber: &WeakEntity<T>,
|
||||
emitter: Entity<Emitter>,
|
||||
event: &Event,
|
||||
cx: &mut App,
|
||||
on_event: &mut dyn FnMut(&mut T, Entity<Emitter>, &Event, &mut Context<T>),
|
||||
) -> bool {
|
||||
if let Some(subscriber) = subscriber.upgrade() {
|
||||
subscriber.update(cx, |subscriber, cx| {
|
||||
on_event(subscriber, emitter, event, cx)
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn invoke_observer_in<T: 'static, W: 'static>(
|
||||
observer: &WeakEntity<T>,
|
||||
observed: &WeakEntity<W>,
|
||||
cx: &mut App,
|
||||
on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Window, &mut Context<T>),
|
||||
) -> bool {
|
||||
let Some((observer, observed)) = observer.upgrade().zip(observed.upgrade()) else {
|
||||
return false;
|
||||
};
|
||||
cx.with_window(observer.entity_id(), |window, cx| {
|
||||
observer.update(cx, |observer, cx| {
|
||||
on_notify(observer, observed, window, cx);
|
||||
});
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn invoke_subscriber_in<T: 'static, Emitter: 'static, Event: 'static>(
|
||||
subscriber: &WeakEntity<T>,
|
||||
emitter: &WeakEntity<Emitter>,
|
||||
event: &dyn Any,
|
||||
cx: &mut App,
|
||||
on_event: &mut dyn FnMut(&mut T, &Entity<Emitter>, &Event, &mut Window, &mut Context<T>),
|
||||
) -> bool {
|
||||
let Some((subscriber, emitter)) = subscriber.upgrade().zip(emitter.upgrade()) else {
|
||||
return false;
|
||||
};
|
||||
let event = event.downcast_ref().expect("invalid event type");
|
||||
cx.with_window(subscriber.entity_id(), |window, cx| {
|
||||
subscriber.update(cx, |subscriber, cx| {
|
||||
on_event(subscriber, &emitter, event, window, cx);
|
||||
});
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn invoke_listener<T: 'static>(
|
||||
view: &WeakEntity<T>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
listener: &dyn Fn(&mut T, &mut Window, &mut Context<T>),
|
||||
) {
|
||||
view.update(cx, |view, cx| listener(view, window, cx)).ok();
|
||||
}
|
||||
+1308
File diff suppressed because it is too large.
Load diff
+284
@@ -0,0 +1,284 @@
|
||||
//! Cross-platform headless app context for tests that need real text shaping.
|
||||
//!
|
||||
//! This replaces the macOS-only `HeadlessMetalAppContext` with a platform-neutral
|
||||
//! implementation backed by `TestPlatform`. Tests supply a real `PlatformTextSystem`
|
||||
//! (e.g. `DirectWriteTextSystem` on Windows, `MacTextSystem` on macOS) to get
|
||||
//! accurate glyph measurements while keeping everything else deterministic.
|
||||
//!
|
||||
//! Optionally, a renderer factory can be provided to enable real GPU rendering
|
||||
//! and screenshot capture via [`HeadlessAppContext::capture_screenshot`].
|
||||
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, App, AppCell, AppContext, AssetSource, BackgroundExecutor, Bounds,
|
||||
Context, Entity, EntityId, ForegroundExecutor, Global, Pixels, PlatformHeadlessRenderer,
|
||||
PlatformTextSystem, Render, Reservation, Size, Task, TestDispatcher, TestPlatform, TextSystem,
|
||||
Window, WindowBounds, WindowHandle, WindowOptions,
|
||||
app::{GpuiBorrow, GpuiMode},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use image::RgbaImage;
|
||||
use std::{future::Future, rc::Rc, sync::Arc, time::Duration};
|
||||
|
||||
/// A cross-platform headless app context for tests that need real text shaping.
|
||||
///
|
||||
/// Unlike the old `HeadlessMetalAppContext`, this works on any platform. It uses
|
||||
/// `TestPlatform` for deterministic scheduling and accepts a pluggable
|
||||
/// `PlatformTextSystem` so tests get real glyph measurements.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// let text_system = Arc::new(gpui_wgpu::CosmicTextSystem::new("fallback"));
|
||||
/// let mut cx = HeadlessAppContext::with_platform(
|
||||
/// text_system,
|
||||
/// Arc::new(Assets),
|
||||
/// || gpui_platform::current_headless_renderer(),
|
||||
/// );
|
||||
/// ```
|
||||
pub struct HeadlessAppContext {
|
||||
/// The underlying app cell.
|
||||
pub app: Rc<AppCell>,
|
||||
/// The background executor for running async tasks.
|
||||
pub background_executor: BackgroundExecutor,
|
||||
/// The foreground executor for running tasks on the main thread.
|
||||
pub foreground_executor: ForegroundExecutor,
|
||||
dispatcher: TestDispatcher,
|
||||
text_system: Arc<TextSystem>,
|
||||
}
|
||||
|
||||
impl HeadlessAppContext {
|
||||
/// Creates a new headless app context with the given text system.
|
||||
pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
|
||||
Self::with_platform(platform_text_system, Arc::new(()), || Ok(None))
|
||||
}
|
||||
|
||||
/// Creates a new headless app context with a custom text system and asset source.
|
||||
pub fn with_asset_source(
|
||||
platform_text_system: Arc<dyn PlatformTextSystem>,
|
||||
asset_source: Arc<dyn AssetSource>,
|
||||
) -> Self {
|
||||
Self::with_platform(platform_text_system, asset_source, || Ok(None))
|
||||
}
|
||||
|
||||
/// Creates a new headless app context with the given text system, asset source,
|
||||
/// and an optional renderer factory for screenshot support.
|
||||
pub fn with_platform(
|
||||
platform_text_system: Arc<dyn PlatformTextSystem>,
|
||||
asset_source: Arc<dyn AssetSource>,
|
||||
renderer_factory: impl Fn() -> Result<Option<Box<dyn PlatformHeadlessRenderer>>> + 'static,
|
||||
) -> Self {
|
||||
let seed = std::env::var("SEED")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
let dispatcher = TestDispatcher::new(seed);
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let renderer_factory: Box<dyn Fn() -> Result<Option<Box<dyn PlatformHeadlessRenderer>>>> =
|
||||
Box::new(renderer_factory);
|
||||
let platform = TestPlatform::with_platform(
|
||||
background_executor.clone(),
|
||||
foreground_executor.clone(),
|
||||
platform_text_system.clone(),
|
||||
Some(renderer_factory),
|
||||
);
|
||||
|
||||
let text_system = Arc::new(TextSystem::new(platform_text_system));
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
app.borrow_mut().mode = GpuiMode::test();
|
||||
|
||||
Self {
|
||||
app,
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
dispatcher,
|
||||
text_system,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a window for headless rendering.
|
||||
pub fn open_window<V: Render + 'static>(
|
||||
&mut self,
|
||||
size: Size<Pixels>,
|
||||
build_root: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> Result<WindowHandle<V>> {
|
||||
use crate::{point, px};
|
||||
|
||||
let bounds = Bounds {
|
||||
origin: point(px(0.0), px(0.0)),
|
||||
size,
|
||||
};
|
||||
|
||||
let mut cx = self.app.borrow_mut();
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
focus: false,
|
||||
show: false,
|
||||
..Default::default()
|
||||
},
|
||||
build_root,
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs all pending tasks until parked.
|
||||
pub fn run_until_parked(&self) {
|
||||
self.dispatcher.run_until_parked();
|
||||
}
|
||||
|
||||
/// Advances the simulated clock.
|
||||
pub fn advance_clock(&self, duration: Duration) {
|
||||
self.dispatcher.advance_clock(duration);
|
||||
}
|
||||
|
||||
/// Enables parking mode, allowing blocking on real I/O (e.g., async asset loading).
|
||||
pub fn allow_parking(&self) {
|
||||
self.dispatcher.allow_parking();
|
||||
}
|
||||
|
||||
/// Disables parking mode, returning to deterministic test execution.
|
||||
pub fn forbid_parking(&self) {
|
||||
self.dispatcher.forbid_parking();
|
||||
}
|
||||
|
||||
/// Updates app state.
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let mut app = self.app.borrow_mut();
|
||||
f(&mut app)
|
||||
}
|
||||
|
||||
/// Updates a window and calls draw to render.
|
||||
pub fn update_window<R>(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
f: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
|
||||
) -> Result<R> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_window(window, f)
|
||||
}
|
||||
|
||||
/// Captures a screenshot from a window.
|
||||
///
|
||||
/// Requires that the context was created with a renderer factory that
|
||||
/// returns `Some` via [`HeadlessAppContext::with_platform`].
|
||||
pub fn capture_screenshot(&mut self, window: AnyWindowHandle) -> Result<RgbaImage> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_window(window, |_, window, _| window.render_to_image())?
|
||||
}
|
||||
|
||||
/// Returns the text system.
|
||||
pub fn text_system(&self) -> &Arc<TextSystem> {
|
||||
&self.text_system
|
||||
}
|
||||
|
||||
/// Returns the background executor.
|
||||
pub fn background_executor(&self) -> &BackgroundExecutor {
|
||||
&self.background_executor
|
||||
}
|
||||
|
||||
/// Returns the foreground executor.
|
||||
pub fn foreground_executor(&self) -> &ForegroundExecutor {
|
||||
&self.foreground_executor
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HeadlessAppContext {
|
||||
fn drop(&mut self) {
|
||||
// Shut down the app so windows are closed and entity handles are
|
||||
// released before the LeakDetector runs.
|
||||
self.app.borrow_mut().shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
impl AppContext for HeadlessAppContext {
|
||||
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.reserve_entity()
|
||||
}
|
||||
|
||||
fn insert_entity<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Entity<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> R {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
panic!("Cannot use as_mut with HeadlessAppContext. Call update() instead.")
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
app.read_entity(handle, read)
|
||||
}
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update_window(window, f)
|
||||
}
|
||||
|
||||
fn with_window<R>(
|
||||
&mut self,
|
||||
entity_id: EntityId,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> R,
|
||||
) -> Option<R> {
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.with_window(entity_id, f)
|
||||
}
|
||||
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
app.read_window(window, read)
|
||||
}
|
||||
|
||||
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
app.read_global(callback)
|
||||
}
|
||||
}
|
||||
Vendored
+645
@@ -0,0 +1,645 @@
|
||||
//! A clean testing API for GPUI applications.
|
||||
//!
|
||||
//! `TestApp` provides a simpler alternative to `TestAppContext` with:
|
||||
//! - Automatic effect flushing after updates
|
||||
//! - Clean window creation and inspection
|
||||
//! - Input simulation helpers
|
||||
//!
|
||||
//! # Example
|
||||
//! ```ignore
|
||||
//! #[test]
|
||||
//! fn test_my_view() {
|
||||
//! let mut app = TestApp::new();
|
||||
//!
|
||||
//! let mut window = app.open_window(|window, cx| {
|
||||
//! MyView::new(window, cx)
|
||||
//! });
|
||||
//!
|
||||
//! window.update(|view, window, cx| {
|
||||
//! view.do_something(cx);
|
||||
//! });
|
||||
//!
|
||||
//! // Check rendered state
|
||||
//! assert_eq!(window.title(), Some("Expected Title"));
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use crate::{
|
||||
AnyWindowHandle, App, AppCell, AppContext, AsyncApp, BackgroundExecutor, BorrowAppContext,
|
||||
Bounds, ClipboardItem, Context, Entity, ForegroundExecutor, Global, InputEvent, Keystroke,
|
||||
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Platform,
|
||||
PlatformTextSystem, Point, Render, Size, Task, TestDispatcher, TestPlatform, TextSystem,
|
||||
Window, WindowBounds, WindowHandle, WindowOptions, app::GpuiMode,
|
||||
};
|
||||
use std::{future::Future, rc::Rc, sync::Arc, time::Duration};
|
||||
|
||||
/// A test application context with a clean API.
|
||||
///
|
||||
/// Unlike `TestAppContext`, `TestApp` automatically flushes effects after
|
||||
/// each update and provides simpler window management.
|
||||
pub struct TestApp {
|
||||
app: Rc<AppCell>,
|
||||
platform: Rc<TestPlatform>,
|
||||
background_executor: BackgroundExecutor,
|
||||
foreground_executor: ForegroundExecutor,
|
||||
#[allow(dead_code)]
|
||||
dispatcher: TestDispatcher,
|
||||
text_system: Arc<TextSystem>,
|
||||
}
|
||||
|
||||
impl TestApp {
|
||||
/// Create a new test application.
|
||||
pub fn new() -> Self {
|
||||
Self::with_seed(0)
|
||||
}
|
||||
|
||||
/// Create a new test application with a specific random seed.
|
||||
pub fn with_seed(seed: u64) -> Self {
|
||||
Self::build(seed, None, Arc::new(()))
|
||||
}
|
||||
|
||||
/// Create a new test application with a custom text system for real font shaping.
|
||||
pub fn with_text_system(text_system: Arc<dyn PlatformTextSystem>) -> Self {
|
||||
Self::build(0, Some(text_system), Arc::new(()))
|
||||
}
|
||||
|
||||
/// Create a new test application with a custom text system and asset source.
|
||||
pub fn with_text_system_and_assets(
|
||||
text_system: Arc<dyn PlatformTextSystem>,
|
||||
asset_source: Arc<dyn crate::AssetSource>,
|
||||
) -> Self {
|
||||
Self::build(0, Some(text_system), asset_source)
|
||||
}
|
||||
|
||||
fn build(
|
||||
seed: u64,
|
||||
platform_text_system: Option<Arc<dyn PlatformTextSystem>>,
|
||||
asset_source: Arc<dyn crate::AssetSource>,
|
||||
) -> Self {
|
||||
let dispatcher = TestDispatcher::new(seed);
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
let platform = match platform_text_system.clone() {
|
||||
Some(ts) => TestPlatform::with_text_system(
|
||||
background_executor.clone(),
|
||||
foreground_executor.clone(),
|
||||
ts,
|
||||
),
|
||||
None => TestPlatform::new(background_executor.clone(), foreground_executor.clone()),
|
||||
};
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
let text_system = Arc::new(TextSystem::new(
|
||||
platform_text_system.unwrap_or_else(|| platform.text_system.clone()),
|
||||
));
|
||||
|
||||
let app = App::new_app(platform.clone(), asset_source, http_client);
|
||||
app.borrow_mut().mode = GpuiMode::test();
|
||||
|
||||
Self {
|
||||
app,
|
||||
platform,
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
dispatcher,
|
||||
text_system,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a closure with mutable access to the App context.
|
||||
/// Automatically runs until parked after the closure completes.
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let result = {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update(f)
|
||||
};
|
||||
self.run_until_parked();
|
||||
result
|
||||
}
|
||||
|
||||
/// Run a closure with read-only access to the App context.
|
||||
pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R {
|
||||
let app = self.app.borrow();
|
||||
f(&app)
|
||||
}
|
||||
|
||||
/// Create a new entity in the app.
|
||||
pub fn new_entity<T: 'static>(
|
||||
&mut self,
|
||||
build: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Entity<T> {
|
||||
self.update(|cx| cx.new(build))
|
||||
}
|
||||
|
||||
/// Update an entity.
|
||||
pub fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
entity: &Entity<T>,
|
||||
f: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> R {
|
||||
self.update(|cx| entity.update(cx, f))
|
||||
}
|
||||
|
||||
/// Read an entity.
|
||||
pub fn read_entity<T: 'static, R>(
|
||||
&self,
|
||||
entity: &Entity<T>,
|
||||
f: impl FnOnce(&T, &App) -> R,
|
||||
) -> R {
|
||||
self.read(|cx| f(entity.read(cx), cx))
|
||||
}
|
||||
|
||||
/// Open a test window with the given root view, using maximized bounds.
|
||||
pub fn open_window<V: Render + 'static>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> TestAppWindow<V> {
|
||||
let bounds = self.read(|cx| Bounds::maximized(None, cx));
|
||||
let handle = self.update(|cx| {
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..Default::default()
|
||||
},
|
||||
|window, cx| cx.new(|cx| build_view(window, cx)),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
TestAppWindow {
|
||||
handle,
|
||||
app: self.app.clone(),
|
||||
platform: self.platform.clone(),
|
||||
background_executor: self.background_executor.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a test window with specific options.
|
||||
pub fn open_window_with_options<V: Render + 'static>(
|
||||
&mut self,
|
||||
options: WindowOptions,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> TestAppWindow<V> {
|
||||
let handle = self.update(|cx| {
|
||||
cx.open_window(options, |window, cx| cx.new(|cx| build_view(window, cx)))
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
TestAppWindow {
|
||||
handle,
|
||||
app: self.app.clone(),
|
||||
platform: self.platform.clone(),
|
||||
background_executor: self.background_executor.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run pending tasks until there's nothing left to do.
|
||||
pub fn run_until_parked(&self) {
|
||||
self.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
/// Advance the simulated clock by the given duration.
|
||||
pub fn advance_clock(&self, duration: Duration) {
|
||||
self.background_executor.advance_clock(duration);
|
||||
}
|
||||
|
||||
/// Spawn a future on the foreground executor.
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R>
|
||||
where
|
||||
Fut: Future<Output = R> + 'static,
|
||||
R: 'static,
|
||||
{
|
||||
self.foreground_executor.spawn(f(self.to_async()))
|
||||
}
|
||||
|
||||
/// Spawn a future on the background executor.
|
||||
pub fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
/// Get an async handle to the app.
|
||||
pub fn to_async(&self) -> AsyncApp {
|
||||
AsyncApp {
|
||||
app: Rc::downgrade(&self.app),
|
||||
background_executor: self.background_executor.clone(),
|
||||
foreground_executor: self.foreground_executor.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the background executor.
|
||||
pub fn background_executor(&self) -> &BackgroundExecutor {
|
||||
&self.background_executor
|
||||
}
|
||||
|
||||
/// Get the foreground executor.
|
||||
pub fn foreground_executor(&self) -> &ForegroundExecutor {
|
||||
&self.foreground_executor
|
||||
}
|
||||
|
||||
/// Get the text system.
|
||||
pub fn text_system(&self) -> &Arc<TextSystem> {
|
||||
&self.text_system
|
||||
}
|
||||
|
||||
/// Check if a global of the given type exists.
|
||||
pub fn has_global<G: Global>(&self) -> bool {
|
||||
self.read(|cx| cx.has_global::<G>())
|
||||
}
|
||||
|
||||
/// Set a global value.
|
||||
pub fn set_global<G: Global>(&mut self, global: G) {
|
||||
self.update(|cx| cx.set_global(global));
|
||||
}
|
||||
|
||||
/// Read a global value.
|
||||
pub fn read_global<G: Global, R>(&self, f: impl FnOnce(&G, &App) -> R) -> R {
|
||||
self.read(|cx| f(cx.global(), cx))
|
||||
}
|
||||
|
||||
/// Update a global value.
|
||||
pub fn update_global<G: Global, R>(&mut self, f: impl FnOnce(&mut G, &mut App) -> R) -> R {
|
||||
self.update(|cx| cx.update_global(f))
|
||||
}
|
||||
|
||||
// Platform simulation methods
|
||||
|
||||
/// Write text to the simulated clipboard.
|
||||
pub fn write_to_clipboard(&self, item: ClipboardItem) {
|
||||
self.platform.write_to_clipboard(item);
|
||||
}
|
||||
|
||||
/// Read from the simulated clipboard.
|
||||
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
self.platform.read_from_clipboard()
|
||||
}
|
||||
|
||||
/// Get URLs that have been opened via `cx.open_url()`.
|
||||
pub fn opened_url(&self) -> Option<String> {
|
||||
self.platform.opened_url.borrow().clone()
|
||||
}
|
||||
|
||||
/// Check if a file path prompt is pending.
|
||||
pub fn did_prompt_for_new_path(&self) -> bool {
|
||||
self.platform.did_prompt_for_new_path()
|
||||
}
|
||||
|
||||
/// Simulate answering a path selection dialog.
|
||||
pub fn simulate_new_path_selection(
|
||||
&self,
|
||||
select: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
|
||||
) {
|
||||
self.platform.simulate_new_path_selection(select);
|
||||
}
|
||||
|
||||
/// Check if a prompt dialog is pending.
|
||||
pub fn has_pending_prompt(&self) -> bool {
|
||||
self.platform.has_pending_prompt()
|
||||
}
|
||||
|
||||
/// Simulate answering a prompt dialog.
|
||||
pub fn simulate_prompt_answer(&self, button: &str) {
|
||||
self.platform.simulate_prompt_answer(button);
|
||||
}
|
||||
|
||||
/// Get all open windows.
|
||||
pub fn windows(&self) -> Vec<AnyWindowHandle> {
|
||||
self.read(|cx| cx.windows())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TestApp {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A test window with inspection and simulation capabilities.
|
||||
pub struct TestAppWindow<V> {
|
||||
handle: WindowHandle<V>,
|
||||
app: Rc<AppCell>,
|
||||
platform: Rc<TestPlatform>,
|
||||
background_executor: BackgroundExecutor,
|
||||
}
|
||||
|
||||
impl<V: 'static + Render> TestAppWindow<V> {
|
||||
/// Get the window handle.
|
||||
pub fn handle(&self) -> WindowHandle<V> {
|
||||
self.handle
|
||||
}
|
||||
|
||||
/// Get the root view entity.
|
||||
pub fn root(&self) -> Entity<V> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
let any_handle: AnyWindowHandle = self.handle.into();
|
||||
app.update_window(any_handle, |root_view, _, _| {
|
||||
root_view.downcast::<V>().expect("root view type mismatch")
|
||||
})
|
||||
.expect("window not found")
|
||||
}
|
||||
|
||||
/// Update the root view.
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R) -> R {
|
||||
let result = {
|
||||
let mut app = self.app.borrow_mut();
|
||||
let any_handle: AnyWindowHandle = self.handle.into();
|
||||
app.update_window(any_handle, |root_view, window, cx| {
|
||||
let view = root_view.downcast::<V>().expect("root view type mismatch");
|
||||
view.update(cx, |view, cx| f(view, window, cx))
|
||||
})
|
||||
.expect("window not found")
|
||||
};
|
||||
self.background_executor.run_until_parked();
|
||||
result
|
||||
}
|
||||
|
||||
/// Read the root view.
|
||||
pub fn read<R>(&self, f: impl FnOnce(&V, &App) -> R) -> R {
|
||||
let app = self.app.borrow();
|
||||
let view = self
|
||||
.app
|
||||
.borrow()
|
||||
.windows
|
||||
.get(self.handle.window_id())
|
||||
.and_then(|w| w.as_ref())
|
||||
.and_then(|w| w.root.clone())
|
||||
.and_then(|r| r.downcast::<V>().ok())
|
||||
.expect("window or root view not found");
|
||||
f(view.read(&app), &app)
|
||||
}
|
||||
|
||||
/// Get the window title.
|
||||
pub fn title(&self) -> Option<String> {
|
||||
let app = self.app.borrow();
|
||||
app.read_window(&self.handle, |_, _cx| {
|
||||
// TODO: expose title through Window API
|
||||
None
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Simulate a keystroke.
|
||||
pub fn simulate_keystroke(&mut self, keystroke: &str) {
|
||||
let keystroke = Keystroke::parse(keystroke).unwrap();
|
||||
{
|
||||
let mut app = self.app.borrow_mut();
|
||||
let any_handle: AnyWindowHandle = self.handle.into();
|
||||
app.update_window(any_handle, |_, window, cx| {
|
||||
window.dispatch_keystroke(keystroke, cx);
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
self.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
/// Simulate multiple keystrokes (space-separated).
|
||||
pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
|
||||
for keystroke in keystrokes.split(' ') {
|
||||
self.simulate_keystroke(keystroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// Simulate typing text.
|
||||
pub fn simulate_input(&mut self, input: &str) {
|
||||
for char in input.chars() {
|
||||
self.simulate_keystroke(&char.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Simulate a mouse move.
|
||||
pub fn simulate_mouse_move(&mut self, position: Point<Pixels>) {
|
||||
self.simulate_event(MouseMoveEvent {
|
||||
position,
|
||||
modifiers: Default::default(),
|
||||
pressed_button: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Simulate a mouse down event.
|
||||
pub fn simulate_mouse_down(&mut self, position: Point<Pixels>, button: MouseButton) {
|
||||
self.simulate_event(MouseDownEvent {
|
||||
position,
|
||||
button,
|
||||
modifiers: Default::default(),
|
||||
click_count: 1,
|
||||
first_mouse: false,
|
||||
});
|
||||
}
|
||||
|
||||
/// Simulate a mouse up event.
|
||||
pub fn simulate_mouse_up(&mut self, position: Point<Pixels>, button: MouseButton) {
|
||||
self.simulate_event(MouseUpEvent {
|
||||
position,
|
||||
button,
|
||||
modifiers: Default::default(),
|
||||
click_count: 1,
|
||||
});
|
||||
}
|
||||
|
||||
/// Simulate a click at the given position.
|
||||
pub fn simulate_click(&mut self, position: Point<Pixels>, button: MouseButton) {
|
||||
self.simulate_mouse_down(position, button);
|
||||
self.simulate_mouse_up(position, button);
|
||||
}
|
||||
|
||||
/// Simulate a scroll event.
|
||||
pub fn simulate_scroll(&mut self, position: Point<Pixels>, delta: Point<Pixels>) {
|
||||
self.simulate_event(crate::ScrollWheelEvent {
|
||||
position,
|
||||
delta: crate::ScrollDelta::Pixels(delta),
|
||||
modifiers: Default::default(),
|
||||
touch_phase: crate::TouchPhase::Moved,
|
||||
});
|
||||
}
|
||||
|
||||
/// Simulate an input event.
|
||||
pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
|
||||
let platform_input = event.to_platform_input();
|
||||
{
|
||||
let mut app = self.app.borrow_mut();
|
||||
let any_handle: AnyWindowHandle = self.handle.into();
|
||||
app.update_window(any_handle, |_, window, cx| {
|
||||
window.dispatch_event(platform_input, cx);
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
self.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
/// Simulate resizing the window.
|
||||
pub fn simulate_resize(&mut self, size: Size<Pixels>) {
|
||||
let window_id = self.handle.window_id();
|
||||
let mut app = self.app.borrow_mut();
|
||||
if let Some(Some(window)) = app.windows.get_mut(window_id) {
|
||||
if let Some(test_window) = window.platform_window.as_test() {
|
||||
test_window.simulate_resize(size);
|
||||
}
|
||||
}
|
||||
drop(app);
|
||||
self.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
/// Simulate the window moving to a display with a different scale factor.
|
||||
pub fn simulate_scale_factor_change(&mut self, scale_factor: f32) {
|
||||
let window_id = self.handle.window_id();
|
||||
let test_window = {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.windows
|
||||
.get_mut(window_id)
|
||||
.and_then(|window| window.as_mut())
|
||||
.and_then(|window| window.platform_window.as_test())
|
||||
.cloned()
|
||||
};
|
||||
// The resize callback needs to borrow the app again synchronously.
|
||||
if let Some(mut test_window) = test_window {
|
||||
test_window.simulate_scale_factor_change(scale_factor);
|
||||
}
|
||||
self.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
/// Force a redraw of the window.
|
||||
pub fn draw(&mut self) {
|
||||
let mut app = self.app.borrow_mut();
|
||||
let any_handle: AnyWindowHandle = self.handle.into();
|
||||
app.update_window(any_handle, |_, window, cx| {
|
||||
window.draw(cx).clear(cx);
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for TestAppWindow<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
handle: self.handle,
|
||||
app: self.app.clone(),
|
||||
platform: self.platform.clone(),
|
||||
background_executor: self.background_executor.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{FocusHandle, Focusable, div, prelude::*};
|
||||
|
||||
struct Counter {
|
||||
count: usize,
|
||||
focus_handle: FocusHandle,
|
||||
}
|
||||
|
||||
impl Counter {
|
||||
fn new(_window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let focus_handle = cx.focus_handle();
|
||||
Self {
|
||||
count: 0,
|
||||
focus_handle,
|
||||
}
|
||||
}
|
||||
|
||||
fn increment(&mut self, _cx: &mut Context<Self>) {
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl Focusable for Counter {
|
||||
fn focus_handle(&self, _cx: &App) -> FocusHandle {
|
||||
self.focus_handle.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Counter {
|
||||
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
|
||||
div().child(format!("Count: {}", self.count))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic_usage() {
|
||||
let mut app = TestApp::new();
|
||||
|
||||
let mut window = app.open_window(Counter::new);
|
||||
|
||||
window.update(|counter, _window, cx| {
|
||||
counter.increment(cx);
|
||||
});
|
||||
|
||||
window.read(|counter, _| {
|
||||
assert_eq!(counter.count, 1);
|
||||
});
|
||||
|
||||
drop(window);
|
||||
app.update(|cx| cx.shutdown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simulate_scale_factor_change() {
|
||||
let mut app = TestApp::new();
|
||||
let mut window = app.open_window(|_, _| crate::EmptyView);
|
||||
let viewport_size = window.update(|_, window, _| {
|
||||
assert_eq!(window.scale_factor(), 2.0);
|
||||
window.viewport_size()
|
||||
});
|
||||
|
||||
window.simulate_scale_factor_change(1.0);
|
||||
|
||||
window.update(|_, window, _| {
|
||||
assert_eq!(window.scale_factor(), 1.0);
|
||||
assert_eq!(window.viewport_size(), viewport_size);
|
||||
});
|
||||
|
||||
drop(window);
|
||||
app.update(|cx| cx.shutdown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_entity_creation() {
|
||||
let mut app = TestApp::new();
|
||||
|
||||
let entity = app.new_entity(|cx| Counter {
|
||||
count: 42,
|
||||
focus_handle: cx.focus_handle(),
|
||||
});
|
||||
|
||||
app.read_entity(&entity, |counter, _| {
|
||||
assert_eq!(counter.count, 42);
|
||||
});
|
||||
|
||||
app.update_entity(&entity, |counter, _cx| {
|
||||
counter.count += 1;
|
||||
});
|
||||
|
||||
app.read_entity(&entity, |counter, _| {
|
||||
assert_eq!(counter.count, 43);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_globals() {
|
||||
let mut app = TestApp::new();
|
||||
|
||||
struct MyGlobal(String);
|
||||
impl Global for MyGlobal {}
|
||||
|
||||
assert!(!app.has_global::<MyGlobal>());
|
||||
|
||||
app.set_global(MyGlobal("hello".into()));
|
||||
|
||||
assert!(app.has_global::<MyGlobal>());
|
||||
|
||||
app.read_global::<MyGlobal, _>(|global, _| {
|
||||
assert_eq!(global.0, "hello");
|
||||
});
|
||||
|
||||
app.update_global::<MyGlobal, _>(|global, _| {
|
||||
global.0 = "world".into();
|
||||
});
|
||||
|
||||
app.read_global::<MyGlobal, _>(|global, _| {
|
||||
assert_eq!(global.0, "world");
|
||||
});
|
||||
}
|
||||
}
|
||||
+1439
File diff suppressed because it is too large.
Load diff
+484
@@ -0,0 +1,484 @@
|
||||
use crate::{
|
||||
Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AssetSource, BackgroundExecutor,
|
||||
Bounds, ClipboardItem, Context, Entity, EntityId, ForegroundExecutor, Global, InputEvent,
|
||||
Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
|
||||
Platform, Point, Render, Result, Size, Task, TestDispatcher, TextSystem, VisualTestPlatform,
|
||||
Window, WindowBounds, WindowHandle, WindowOptions, app::GpuiMode,
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use image::RgbaImage;
|
||||
use std::{future::Future, rc::Rc, sync::Arc, time::Duration};
|
||||
|
||||
/// A test context that uses real macOS rendering instead of mocked rendering.
|
||||
/// This is used for visual tests that need to capture actual screenshots.
|
||||
///
|
||||
/// Unlike `TestAppContext` which uses `TestPlatform` with mocked rendering,
|
||||
/// `VisualTestAppContext` uses the real `MacPlatform` to produce actual rendered output.
|
||||
///
|
||||
/// Windows created through this context are positioned off-screen (at coordinates like -10000, -10000)
|
||||
/// so they are invisible to the user but still fully rendered by the compositor.
|
||||
#[derive(Clone)]
|
||||
pub struct VisualTestAppContext {
|
||||
/// The underlying app cell
|
||||
pub app: Rc<AppCell>,
|
||||
/// The background executor for running async tasks
|
||||
pub background_executor: BackgroundExecutor,
|
||||
/// The foreground executor for running tasks on the main thread
|
||||
pub foreground_executor: ForegroundExecutor,
|
||||
/// The test dispatcher for deterministic task scheduling
|
||||
dispatcher: TestDispatcher,
|
||||
platform: Rc<dyn Platform>,
|
||||
text_system: Arc<TextSystem>,
|
||||
}
|
||||
|
||||
impl VisualTestAppContext {
|
||||
/// Creates a new `VisualTestAppContext` with real macOS platform rendering
|
||||
/// but deterministic task scheduling via TestDispatcher.
|
||||
///
|
||||
/// This provides:
|
||||
/// - Real Metal/compositor rendering for accurate screenshots
|
||||
/// - Deterministic task scheduling via TestDispatcher
|
||||
/// - Controllable time via `advance_clock`
|
||||
///
|
||||
/// Note: This uses a no-op asset source, so SVG icons won't render.
|
||||
/// Use `with_asset_source` to provide real assets for icon rendering.
|
||||
pub fn new(platform: Rc<dyn Platform>) -> Self {
|
||||
Self::with_asset_source(platform, Arc::new(()))
|
||||
}
|
||||
|
||||
/// Creates a new `VisualTestAppContext` with a custom asset source.
|
||||
///
|
||||
/// Use this when you need SVG icons to render properly in visual tests.
|
||||
/// Pass the real `Assets` struct to enable icon rendering.
|
||||
pub fn with_asset_source(
|
||||
platform: Rc<dyn Platform>,
|
||||
asset_source: Arc<dyn AssetSource>,
|
||||
) -> Self {
|
||||
// Use a seeded RNG for deterministic behavior
|
||||
let seed = std::env::var("SEED")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
// Create a visual test platform that combines real Mac rendering
|
||||
// with controllable TestDispatcher for deterministic task scheduling
|
||||
let platform = Rc::new(VisualTestPlatform::new(platform, seed));
|
||||
|
||||
// Get the dispatcher and executors from the platform
|
||||
let dispatcher = platform.dispatcher().clone();
|
||||
let background_executor = platform.background_executor();
|
||||
let foreground_executor = platform.foreground_executor();
|
||||
|
||||
let text_system = Arc::new(TextSystem::new(platform.text_system()));
|
||||
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let mut app = App::new_app(platform.clone(), asset_source, http_client);
|
||||
app.borrow_mut().mode = GpuiMode::test();
|
||||
|
||||
Self {
|
||||
app,
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
dispatcher,
|
||||
platform,
|
||||
text_system,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a window positioned off-screen for invisible rendering.
|
||||
///
|
||||
/// The window is positioned at (-10000, -10000) so it's not visible on any display,
|
||||
/// but it's still fully rendered by the compositor and can be captured via ScreenCaptureKit.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `size` - The size of the window to create
|
||||
/// * `build_root` - A closure that builds the root view for the window
|
||||
pub fn open_offscreen_window<V: Render + 'static>(
|
||||
&mut self,
|
||||
size: Size<Pixels>,
|
||||
build_root: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> Result<WindowHandle<V>> {
|
||||
use crate::{point, px};
|
||||
|
||||
let bounds = Bounds {
|
||||
origin: point(px(-10000.0), px(-10000.0)),
|
||||
size,
|
||||
};
|
||||
|
||||
let mut cx = self.app.borrow_mut();
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
focus: false,
|
||||
show: true,
|
||||
..Default::default()
|
||||
},
|
||||
build_root,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens an off-screen window with default size (1280x800).
|
||||
pub fn open_offscreen_window_default<V: Render + 'static>(
|
||||
&mut self,
|
||||
build_root: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> Result<WindowHandle<V>> {
|
||||
use crate::{px, size};
|
||||
self.open_offscreen_window(size(px(1280.0), px(800.0)), build_root)
|
||||
}
|
||||
|
||||
/// Returns whether screen capture is supported on this platform.
|
||||
pub fn is_screen_capture_supported(&self) -> bool {
|
||||
self.platform.is_screen_capture_supported()
|
||||
}
|
||||
|
||||
/// Returns the text system used by this context.
|
||||
pub fn text_system(&self) -> &Arc<TextSystem> {
|
||||
&self.text_system
|
||||
}
|
||||
|
||||
/// Returns the background executor.
|
||||
pub fn executor(&self) -> BackgroundExecutor {
|
||||
self.background_executor.clone()
|
||||
}
|
||||
|
||||
/// Returns the foreground executor.
|
||||
pub fn foreground_executor(&self) -> ForegroundExecutor {
|
||||
self.foreground_executor.clone()
|
||||
}
|
||||
|
||||
/// Runs all pending foreground and background tasks until there's nothing left to do.
|
||||
/// This is essential for processing async operations like tooltip timers.
|
||||
pub fn run_until_parked(&self) {
|
||||
self.dispatcher.run_until_parked();
|
||||
}
|
||||
|
||||
/// Advances the simulated clock by the given duration and processes any tasks
|
||||
/// that become ready. This is essential for testing time-based behaviors like
|
||||
/// tooltip delays.
|
||||
pub fn advance_clock(&self, duration: Duration) {
|
||||
self.dispatcher.advance_clock(duration);
|
||||
}
|
||||
|
||||
/// Updates the app state.
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let mut app = self.app.borrow_mut();
|
||||
f(&mut app)
|
||||
}
|
||||
|
||||
/// Reads from the app state.
|
||||
pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R {
|
||||
let app = self.app.borrow();
|
||||
f(&app)
|
||||
}
|
||||
|
||||
/// Updates a window.
|
||||
pub fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update_window(window, f)
|
||||
}
|
||||
|
||||
/// Spawns a task on the foreground executor.
|
||||
pub fn spawn<F, R>(&self, f: F) -> Task<R>
|
||||
where
|
||||
F: Future<Output = R> + 'static,
|
||||
R: 'static,
|
||||
{
|
||||
self.foreground_executor.spawn(f)
|
||||
}
|
||||
|
||||
/// Checks if a global of type G exists.
|
||||
pub fn has_global<G: Global>(&self) -> bool {
|
||||
let app = self.app.borrow();
|
||||
app.has_global::<G>()
|
||||
}
|
||||
|
||||
/// Reads a global value.
|
||||
pub fn read_global<G: Global, R>(&self, f: impl FnOnce(&G, &App) -> R) -> R {
|
||||
let app = self.app.borrow();
|
||||
f(app.global::<G>(), &app)
|
||||
}
|
||||
|
||||
/// Sets a global value.
|
||||
pub fn set_global<G: Global>(&mut self, global: G) {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.set_global(global);
|
||||
}
|
||||
|
||||
/// Updates a global value.
|
||||
pub fn update_global<G: Global, R>(&mut self, f: impl FnOnce(&mut G, &mut App) -> R) -> R {
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update(|cx| {
|
||||
let mut global = cx.lease_global::<G>();
|
||||
let result = f(&mut global, cx);
|
||||
cx.end_global_lease(global);
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
/// Simulates a sequence of keystrokes on the given window.
|
||||
///
|
||||
/// Keystrokes are specified as a space-separated string, e.g., "cmd-p escape".
|
||||
pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
|
||||
for keystroke_text in keystrokes.split_whitespace() {
|
||||
let keystroke = Keystroke::parse(keystroke_text)
|
||||
.unwrap_or_else(|_| panic!("Invalid keystroke: {}", keystroke_text));
|
||||
self.dispatch_keystroke(window, keystroke);
|
||||
}
|
||||
self.run_until_parked();
|
||||
}
|
||||
|
||||
/// Dispatches a single keystroke to a window.
|
||||
pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) {
|
||||
self.update_window(window, |_, window, cx| {
|
||||
window.dispatch_keystroke(keystroke, cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// Simulates typing text input on the given window.
|
||||
pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
|
||||
for char in input.chars() {
|
||||
let key = char.to_string();
|
||||
let keystroke = Keystroke {
|
||||
modifiers: Modifiers::default(),
|
||||
key: key.clone(),
|
||||
key_char: Some(key),
|
||||
};
|
||||
self.dispatch_keystroke(window, keystroke);
|
||||
}
|
||||
self.run_until_parked();
|
||||
}
|
||||
|
||||
/// Simulates a mouse move event.
|
||||
pub fn simulate_mouse_move(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
position: Point<Pixels>,
|
||||
button: impl Into<Option<MouseButton>>,
|
||||
modifiers: Modifiers,
|
||||
) {
|
||||
self.simulate_event(
|
||||
window,
|
||||
MouseMoveEvent {
|
||||
position,
|
||||
modifiers,
|
||||
pressed_button: button.into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Simulates a mouse down event.
|
||||
pub fn simulate_mouse_down(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
position: Point<Pixels>,
|
||||
button: MouseButton,
|
||||
modifiers: Modifiers,
|
||||
) {
|
||||
self.simulate_event(
|
||||
window,
|
||||
MouseDownEvent {
|
||||
position,
|
||||
modifiers,
|
||||
button,
|
||||
click_count: 1,
|
||||
first_mouse: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Simulates a mouse up event.
|
||||
pub fn simulate_mouse_up(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
position: Point<Pixels>,
|
||||
button: MouseButton,
|
||||
modifiers: Modifiers,
|
||||
) {
|
||||
self.simulate_event(
|
||||
window,
|
||||
MouseUpEvent {
|
||||
position,
|
||||
modifiers,
|
||||
button,
|
||||
click_count: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Simulates a click (mouse down followed by mouse up).
|
||||
pub fn simulate_click(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
position: Point<Pixels>,
|
||||
modifiers: Modifiers,
|
||||
) {
|
||||
self.simulate_mouse_down(window, position, MouseButton::Left, modifiers);
|
||||
self.simulate_mouse_up(window, position, MouseButton::Left, modifiers);
|
||||
}
|
||||
|
||||
/// Simulates an input event on the given window.
|
||||
pub fn simulate_event<E: InputEvent>(&mut self, window: AnyWindowHandle, event: E) {
|
||||
self.update_window(window, |_, window, cx| {
|
||||
window.dispatch_event(event.to_platform_input(), cx);
|
||||
})
|
||||
.ok();
|
||||
self.run_until_parked();
|
||||
}
|
||||
|
||||
/// Dispatches an action to the given window.
|
||||
pub fn dispatch_action(&mut self, window: AnyWindowHandle, action: impl Action) {
|
||||
self.update_window(window, |_, window, cx| {
|
||||
window.dispatch_action(action.boxed_clone(), cx);
|
||||
})
|
||||
.ok();
|
||||
self.run_until_parked();
|
||||
}
|
||||
|
||||
/// Writes to the clipboard.
|
||||
pub fn write_to_clipboard(&self, item: ClipboardItem) {
|
||||
self.platform.write_to_clipboard(item);
|
||||
}
|
||||
|
||||
/// Reads from the clipboard.
|
||||
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
self.platform.read_from_clipboard()
|
||||
}
|
||||
|
||||
/// Waits for a condition to become true, with a timeout.
|
||||
pub async fn wait_for<T: 'static>(
|
||||
&mut self,
|
||||
entity: &Entity<T>,
|
||||
predicate: impl Fn(&T) -> bool,
|
||||
timeout: Duration,
|
||||
) -> Result<()> {
|
||||
let start = web_time::Instant::now();
|
||||
loop {
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
if predicate(entity.read(&app)) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if start.elapsed() > timeout {
|
||||
return Err(anyhow!("Timed out waiting for condition"));
|
||||
}
|
||||
|
||||
self.run_until_parked();
|
||||
self.background_executor
|
||||
.timer(Duration::from_millis(10))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures a screenshot of the specified window using direct texture capture.
|
||||
///
|
||||
/// This renders the scene to a Metal texture and reads the pixels directly,
|
||||
/// which does not require the window to be visible on screen.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn capture_screenshot(&mut self, window: AnyWindowHandle) -> Result<RgbaImage> {
|
||||
self.update_window(window, |_, window, _cx| window.render_to_image())?
|
||||
}
|
||||
|
||||
/// Waits for animations to complete by waiting a couple of frames.
|
||||
pub async fn wait_for_animations(&self) {
|
||||
self.background_executor
|
||||
.timer(Duration::from_millis(32))
|
||||
.await;
|
||||
self.run_until_parked();
|
||||
}
|
||||
}
|
||||
|
||||
impl AppContext for VisualTestAppContext {
|
||||
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.reserve_entity()
|
||||
}
|
||||
|
||||
fn insert_entity<T: 'static>(
|
||||
&mut self,
|
||||
reservation: crate::Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Entity<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> R {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> crate::GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
panic!("Cannot use as_mut with a visual test app context. Try calling update() first")
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
app.read_entity(handle, read)
|
||||
}
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update_window(window, f)
|
||||
}
|
||||
|
||||
fn with_window<R>(
|
||||
&mut self,
|
||||
entity_id: EntityId,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> R,
|
||||
) -> Option<R> {
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.with_window(entity_id, f)
|
||||
}
|
||||
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
app.read_window(window, read)
|
||||
}
|
||||
|
||||
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
let app = self.app.borrow();
|
||||
callback(app.global::<G>(), &app)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user