Compare commits
12 Commits
main
...
actually-r
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10e852c051 | ||
|
|
2fe854df51 | ||
|
|
068d6d814e | ||
|
|
ae9139ba5a | ||
|
|
f6a406b8da | ||
|
|
72bd8a78db | ||
|
|
c00cd2c587 | ||
|
|
626bd86e62 | ||
|
|
98a0075c21 | ||
|
|
28dc83f076 | ||
|
|
02b1387e61 | ||
|
|
688d2952c8 |
@@ -580,6 +580,7 @@ impl GpuiMode {
|
||||
/// You need a reference to an `App` to access the state of a [Entity].
|
||||
pub struct App {
|
||||
pub(crate) this: Weak<AppCell>,
|
||||
pub(crate) liveness: std::sync::Arc<()>,
|
||||
pub(crate) platform: Rc<dyn Platform>,
|
||||
pub(crate) mode: GpuiMode,
|
||||
text_system: Arc<TextSystem>,
|
||||
@@ -658,6 +659,7 @@ impl App {
|
||||
let app = Rc::new_cyclic(|this| AppCell {
|
||||
app: RefCell::new(App {
|
||||
this: this.clone(),
|
||||
liveness: std::sync::Arc::new(()),
|
||||
platform: platform.clone(),
|
||||
text_system,
|
||||
mode: GpuiMode::Production,
|
||||
@@ -1476,6 +1478,7 @@ impl App {
|
||||
pub fn to_async(&self) -> AsyncApp {
|
||||
AsyncApp {
|
||||
app: self.this.clone(),
|
||||
liveness_token: std::sync::Arc::downgrade(&self.liveness),
|
||||
background_executor: self.background_executor.clone(),
|
||||
foreground_executor: self.foreground_executor.clone(),
|
||||
}
|
||||
@@ -2212,8 +2215,6 @@ impl App {
|
||||
}
|
||||
|
||||
impl AppContext for App {
|
||||
type Result<T> = T;
|
||||
|
||||
/// Builds an entity that is owned by the application.
|
||||
///
|
||||
/// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
|
||||
@@ -2235,7 +2236,7 @@ impl AppContext for App {
|
||||
})
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
|
||||
Reservation(self.entities.reserve())
|
||||
}
|
||||
|
||||
@@ -2243,7 +2244,7 @@ impl AppContext for App {
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
) -> Entity<T> {
|
||||
self.update(|cx| {
|
||||
let slot = reservation.0;
|
||||
let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
|
||||
@@ -2276,11 +2277,7 @@ impl AppContext for App {
|
||||
GpuiBorrow::new(handle.clone(), self)
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -2325,7 +2322,7 @@ impl AppContext for App {
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
|
||||
Entity, EventEmitter, Focusable, ForegroundExecutor, Global, PromptButton, PromptLevel, Render,
|
||||
Reservation, Result, Subscription, Task, VisualContext, Window, WindowHandle,
|
||||
Entity, EventEmitter, Focusable, ForegroundExecutor, Global, GpuiBorrow, PromptButton,
|
||||
PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext, Window,
|
||||
WindowHandle,
|
||||
};
|
||||
use anyhow::{Context as _, anyhow};
|
||||
use anyhow::Context as _;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use futures::channel::oneshot;
|
||||
use std::{future::Future, rc::Weak};
|
||||
@@ -12,72 +13,73 @@ 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`, so its methods are fallible to protect against cases where the [App] is dropped.
|
||||
///
|
||||
/// 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) liveness_token: std::sync::Weak<()>,
|
||||
pub(crate) background_executor: BackgroundExecutor,
|
||||
pub(crate) foreground_executor: ForegroundExecutor,
|
||||
}
|
||||
|
||||
impl AppContext for AsyncApp {
|
||||
type Result<T> = Result<T>;
|
||||
impl AsyncApp {
|
||||
fn app(&self) -> std::rc::Rc<AppCell> {
|
||||
self.app
|
||||
.upgrade()
|
||||
.expect("app was released before async operation completed")
|
||||
}
|
||||
}
|
||||
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
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();
|
||||
Ok(app.new(build_entity))
|
||||
app.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
Ok(app.reserve_entity())
|
||||
app.reserve_entity()
|
||||
}
|
||||
|
||||
fn insert_entity<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Result<Entity<T>> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
) -> Entity<T> {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
Ok(app.insert_entity(reservation, build_entity))
|
||||
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,
|
||||
) -> Self::Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
) -> R {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
Ok(app.update_entity(handle, update))
|
||||
app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
|
||||
fn as_mut<'a, T>(&'a mut self, _handle: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
Err(anyhow!(
|
||||
"Cannot as_mut with an async context. Try calling update() first"
|
||||
))
|
||||
panic!("Cannot as_mut with an async context. Try calling update() first")
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
callback: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, callback: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let app = self.app();
|
||||
let lock = app.borrow();
|
||||
Ok(lock.read_entity(handle, callback))
|
||||
lock.read_entity(handle, callback)
|
||||
}
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
@@ -109,23 +111,22 @@ impl AppContext for AsyncApp {
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
Ok(lock.update(|this| this.read_global(callback)))
|
||||
lock.update(|this| this.read_global(callback))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncApp {
|
||||
/// Schedules all windows in the application to be redrawn.
|
||||
pub fn refresh(&self) -> Result<()> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
pub fn refresh(&self) {
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.refresh_windows();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get an executor which can be used to spawn futures in the background.
|
||||
@@ -139,10 +140,10 @@ impl AsyncApp {
|
||||
}
|
||||
|
||||
/// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
Ok(lock.update(f))
|
||||
lock.update(f)
|
||||
}
|
||||
|
||||
/// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
|
||||
@@ -150,16 +151,15 @@ impl AsyncApp {
|
||||
pub fn subscribe<T, Event>(
|
||||
&mut self,
|
||||
entity: &Entity<T>,
|
||||
mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
|
||||
) -> Result<Subscription>
|
||||
on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static + EventEmitter<Event>,
|
||||
Event: 'static,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
let subscription = lock.subscribe(entity, on_event);
|
||||
Ok(subscription)
|
||||
lock.subscribe(entity, on_event)
|
||||
}
|
||||
|
||||
/// Open a window with the given options based on the root view returned by the given function.
|
||||
@@ -171,7 +171,7 @@ impl AsyncApp {
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let app = self.app();
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.open_window(options, build_root_view)
|
||||
}
|
||||
@@ -185,65 +185,54 @@ impl AsyncApp {
|
||||
{
|
||||
let mut cx = self.clone();
|
||||
self.foreground_executor
|
||||
.spawn(async move { f(&mut cx).await })
|
||||
.spawn_context(self.liveness_token.clone(), async move { f(&mut cx).await })
|
||||
}
|
||||
|
||||
/// Determine whether global state of the specified type has been assigned.
|
||||
/// Returns an error if the `App` has been dropped.
|
||||
pub fn has_global<G: Global>(&self) -> Result<bool> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
pub fn has_global<G: Global>(&self) -> bool {
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
Ok(app.has_global::<G>())
|
||||
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.
|
||||
/// Returns an error if the `App` has been dropped.
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
Ok(read(app.global(), &app))
|
||||
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
|
||||
/// if no state of the specified type has been assigned.
|
||||
///
|
||||
/// Returns an error if no state of the specified type has been assigned the `App` has been dropped.
|
||||
pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
|
||||
let app = self.app.upgrade()?;
|
||||
let app = self.app();
|
||||
let app = app.borrow_mut();
|
||||
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.
|
||||
///
|
||||
/// # Errors
|
||||
/// If the app has ben dropped this returns an error.
|
||||
pub fn try_read_default_global<G: Global + Default, R>(
|
||||
pub fn read_default_global<G: Global + Default, R>(
|
||||
&self,
|
||||
read: impl FnOnce(&G, &App) -> R,
|
||||
) -> Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
) -> R {
|
||||
let app = self.app();
|
||||
let mut app = app.borrow_mut();
|
||||
app.update(|cx| {
|
||||
cx.default_global::<G>();
|
||||
});
|
||||
Ok(read(app.try_global().context("app was released")?, &app))
|
||||
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,
|
||||
) -> Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
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();
|
||||
Ok(app.update(|cx| cx.update_global(update)))
|
||||
app.update(|cx| cx.update_global(update))
|
||||
}
|
||||
|
||||
/// Run something using this entity and cx, when the returned struct is dropped
|
||||
@@ -334,7 +323,10 @@ impl AsyncWindowContext {
|
||||
{
|
||||
let mut cx = self.clone();
|
||||
self.foreground_executor
|
||||
.spawn(async move { f(&mut cx).await })
|
||||
.spawn_context(
|
||||
self.app.liveness_token.clone(),
|
||||
async move { f(&mut cx).await },
|
||||
)
|
||||
}
|
||||
|
||||
/// Present a platform dialog.
|
||||
@@ -359,54 +351,41 @@ impl AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl AppContext for AsyncWindowContext {
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Result<Entity<T>>
|
||||
fn new<T>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.app
|
||||
.update_window(self.window, |_, _, cx| cx.new(build_entity))
|
||||
self.app.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Result<Reservation<T>> {
|
||||
self.app
|
||||
.update_window(self.window, |_, _, cx| cx.reserve_entity())
|
||||
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,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.app.update_window(self.window, |_, _, cx| {
|
||||
cx.insert_entity(reservation, build_entity)
|
||||
})
|
||||
) -> Entity<T> {
|
||||
self.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,
|
||||
) -> Result<R> {
|
||||
self.app
|
||||
.update_window(self.window, |_, _, cx| cx.update_entity(handle, update))
|
||||
) -> R {
|
||||
self.app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
Err(anyhow!(
|
||||
"Cannot use as_mut() from an async context, call `update`"
|
||||
))
|
||||
panic!("Cannot use as_mut() from an async context, call `update`")
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -438,7 +417,7 @@ impl AppContext for AsyncWindowContext {
|
||||
self.app.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
@@ -454,7 +433,7 @@ impl VisualContext for AsyncWindowContext {
|
||||
fn new_window_entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
) -> Result<Entity<T>> {
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
cx.new(|cx| build_entity(window, cx))
|
||||
})
|
||||
@@ -464,7 +443,7 @@ impl VisualContext for AsyncWindowContext {
|
||||
&mut self,
|
||||
view: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
) -> Result<R> {
|
||||
self.app.update_window(self.window, |_, window, cx| {
|
||||
view.update(cx, |entity, cx| update(entity, window, cx))
|
||||
})
|
||||
@@ -473,7 +452,7 @@ impl VisualContext for AsyncWindowContext {
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
) -> Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
@@ -482,7 +461,7 @@ impl VisualContext for AsyncWindowContext {
|
||||
})
|
||||
}
|
||||
|
||||
fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
|
||||
fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
|
||||
where
|
||||
V: Focusable,
|
||||
{
|
||||
|
||||
@@ -753,8 +753,6 @@ impl<T> Context<'_, T> {
|
||||
}
|
||||
|
||||
impl<T> AppContext for Context<'_, T> {
|
||||
type Result<U> = U;
|
||||
|
||||
#[inline]
|
||||
fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
|
||||
self.app.new(build_entity)
|
||||
@@ -770,7 +768,7 @@ impl<T> AppContext for Context<'_, T> {
|
||||
&mut self,
|
||||
reservation: Reservation<U>,
|
||||
build_entity: impl FnOnce(&mut Context<U>) -> U,
|
||||
) -> Self::Result<Entity<U>> {
|
||||
) -> Entity<U> {
|
||||
self.app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
@@ -784,7 +782,7 @@ impl<T> AppContext for Context<'_, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> Self::Result<super::GpuiBorrow<'a, E>>
|
||||
fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> super::GpuiBorrow<'a, E>
|
||||
where
|
||||
E: 'static,
|
||||
{
|
||||
@@ -792,11 +790,7 @@ impl<T> AppContext for Context<'_, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_entity<U, R>(
|
||||
&self,
|
||||
handle: &Entity<U>,
|
||||
read: impl FnOnce(&U, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<U, R>(&self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R) -> R
|
||||
where
|
||||
U: 'static,
|
||||
{
|
||||
@@ -832,7 +826,7 @@ impl<T> AppContext for Context<'_, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
|
||||
@@ -431,11 +431,7 @@ impl<T: 'static> Entity<T> {
|
||||
|
||||
/// Read the entity referenced by this handle with the given function.
|
||||
#[inline]
|
||||
pub fn read_with<R, C: AppContext>(
|
||||
&self,
|
||||
cx: &C,
|
||||
f: impl FnOnce(&T, &App) -> R,
|
||||
) -> C::Result<R> {
|
||||
pub fn read_with<R, C: AppContext>(&self, cx: &C, f: impl FnOnce(&T, &App) -> R) -> R {
|
||||
cx.read_entity(self, f)
|
||||
}
|
||||
|
||||
@@ -445,18 +441,18 @@ impl<T: 'static> Entity<T> {
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> C::Result<R> {
|
||||
) -> R {
|
||||
cx.update_entity(self, update)
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this handle with the given function.
|
||||
#[inline]
|
||||
pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> C::Result<GpuiBorrow<'a, T>> {
|
||||
pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> GpuiBorrow<'a, T> {
|
||||
cx.as_mut(self)
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this handle with the given function.
|
||||
pub fn write<C: AppContext>(&self, cx: &mut C, value: T) -> C::Result<()> {
|
||||
pub fn write<C: AppContext>(&self, cx: &mut C, value: T) {
|
||||
self.update(cx, |entity, cx| {
|
||||
*entity = value;
|
||||
cx.notify();
|
||||
@@ -465,13 +461,13 @@ impl<T: 'static> Entity<T> {
|
||||
|
||||
/// Updates the entity referenced by this handle with the given function if
|
||||
/// the referenced entity still exists, within a visual context that has a window.
|
||||
/// Returns an error if the entity has been released.
|
||||
/// Returns an error if the window has been closed.
|
||||
#[inline]
|
||||
pub fn update_in<R, C: VisualContext>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> C::Result<R> {
|
||||
) -> Result<R> {
|
||||
cx.update_window_entity(self, update)
|
||||
}
|
||||
}
|
||||
@@ -749,13 +745,9 @@ impl<T: 'static> WeakEntity<T> {
|
||||
) -> Result<R>
|
||||
where
|
||||
C: AppContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
crate::Flatten::flatten(
|
||||
self.upgrade()
|
||||
.context("entity released")
|
||||
.map(|this| cx.update_entity(&this, update)),
|
||||
)
|
||||
let entity = self.upgrade().context("entity released")?;
|
||||
Ok(cx.update_entity(&entity, update))
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this handle with the given function if
|
||||
@@ -768,14 +760,13 @@ impl<T: 'static> WeakEntity<T> {
|
||||
) -> Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
let window = cx.window_handle();
|
||||
let this = self.upgrade().context("entity released")?;
|
||||
let entity = self.upgrade().context("entity released")?;
|
||||
|
||||
crate::Flatten::flatten(window.update(cx, |_, window, cx| {
|
||||
this.update(cx, |entity, cx| update(entity, window, cx))
|
||||
}))
|
||||
window.update(cx, |_, window, cx| {
|
||||
entity.update(cx, |entity, cx| update(entity, window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the entity referenced by this handle with the given function if
|
||||
@@ -784,13 +775,9 @@ impl<T: 'static> WeakEntity<T> {
|
||||
pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
|
||||
where
|
||||
C: AppContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
crate::Flatten::flatten(
|
||||
self.upgrade()
|
||||
.context("entity released")
|
||||
.map(|this| cx.read_entity(&this, read)),
|
||||
)
|
||||
let entity = self.upgrade().context("entity released")?;
|
||||
Ok(cx.read_entity(&entity, read))
|
||||
}
|
||||
|
||||
/// Create a new weak entity that can never be upgraded.
|
||||
|
||||
@@ -33,17 +33,12 @@ pub struct TestAppContext {
|
||||
}
|
||||
|
||||
impl AppContext for TestAppContext {
|
||||
type Result<T> = T;
|
||||
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
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) -> Self::Result<crate::Reservation<T>> {
|
||||
fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.reserve_entity()
|
||||
}
|
||||
@@ -52,7 +47,7 @@ impl AppContext for TestAppContext {
|
||||
&mut self,
|
||||
reservation: crate::Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
) -> Entity<T> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.insert_entity(reservation, build_entity)
|
||||
}
|
||||
@@ -61,23 +56,19 @@ impl AppContext for TestAppContext {
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
) -> R {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
|
||||
fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> super::GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
panic!("Cannot use as_mut with a test app context. Try calling update() first")
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -112,7 +103,7 @@ impl AppContext for TestAppContext {
|
||||
self.background_executor.spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
@@ -405,6 +396,7 @@ impl TestAppContext {
|
||||
pub fn to_async(&self) -> AsyncApp {
|
||||
AsyncApp {
|
||||
app: Rc::downgrade(&self.app),
|
||||
liveness_token: std::sync::Arc::downgrade(&self.app.borrow().liveness),
|
||||
background_executor: self.background_executor.clone(),
|
||||
foreground_executor: self.foreground_executor.clone(),
|
||||
}
|
||||
@@ -916,16 +908,11 @@ impl VisualTestContext {
|
||||
}
|
||||
|
||||
impl AppContext for VisualTestContext {
|
||||
type Result<T> = <TestAppContext as AppContext>::Result<T>;
|
||||
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
|
||||
self.cx.new(build_entity)
|
||||
}
|
||||
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
|
||||
fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> {
|
||||
self.cx.reserve_entity()
|
||||
}
|
||||
|
||||
@@ -933,7 +920,7 @@ impl AppContext for VisualTestContext {
|
||||
&mut self,
|
||||
reservation: crate::Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
) -> Entity<T> {
|
||||
self.cx.insert_entity(reservation, build_entity)
|
||||
}
|
||||
|
||||
@@ -941,25 +928,21 @@ impl AppContext for VisualTestContext {
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R>
|
||||
) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.cx.update_entity(handle, update)
|
||||
}
|
||||
|
||||
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<super::GpuiBorrow<'a, T>>
|
||||
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> super::GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.cx.as_mut(handle)
|
||||
}
|
||||
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -991,7 +974,7 @@ impl AppContext for VisualTestContext {
|
||||
self.cx.background_spawn(future)
|
||||
}
|
||||
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
@@ -1008,46 +991,38 @@ impl VisualContext for VisualTestContext {
|
||||
fn new_window_entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
cx.new(|cx| build_entity(window, cx))
|
||||
})
|
||||
.unwrap()
|
||||
) -> Result<Entity<T>> {
|
||||
self.window.update(&mut self.cx, |_, window, cx| {
|
||||
cx.new(|cx| build_entity(window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
fn update_window_entity<V: 'static, R>(
|
||||
&mut self,
|
||||
view: &Entity<V>,
|
||||
update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
view.update(cx, |v, cx| update(v, window, cx))
|
||||
})
|
||||
.unwrap()
|
||||
) -> Result<R> {
|
||||
self.window.update(&mut self.cx, |_, window, cx| {
|
||||
view.update(cx, |v, cx| update(v, window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
) -> Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
self.window
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
window.replace_root(cx, build_view)
|
||||
})
|
||||
.unwrap()
|
||||
self.window.update(&mut self.cx, |_, window, cx| {
|
||||
window.replace_root(cx, build_view)
|
||||
})
|
||||
}
|
||||
|
||||
fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) -> Self::Result<()> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
view.read(cx).focus_handle(cx).focus(window, cx)
|
||||
})
|
||||
.unwrap()
|
||||
fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) -> Result<()> {
|
||||
self.window.update(&mut self.cx, |_, window, cx| {
|
||||
view.read(cx).focus_handle(cx).focus(window, cx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -125,6 +125,30 @@ impl<T> Task<T> {
|
||||
Task(TaskState::Spawned(task)) => task.detach(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this task into a fallible task that returns `Option<T>`.
|
||||
///
|
||||
/// Unlike the standard `Task<T>`, a [`FallibleTask`] will return `None`
|
||||
/// if the app was dropped while the task is executing.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Background task that gracefully handles app shutdown:
|
||||
/// cx.background_spawn(async move {
|
||||
/// let result = foreground_task.fallible().await;
|
||||
/// if let Some(value) = result {
|
||||
/// // Process the value
|
||||
/// }
|
||||
/// // If None, app was shut down - just exit gracefully
|
||||
/// }).detach();
|
||||
/// ```
|
||||
pub fn fallible(self) -> FallibleTask<T> {
|
||||
FallibleTask(match self.0 {
|
||||
TaskState::Ready(val) => FallibleTaskState::Ready(val),
|
||||
TaskState::Spawned(task) => FallibleTaskState::Spawned(task.fallible()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, T> Task<Result<T, E>>
|
||||
@@ -154,6 +178,55 @@ impl<T> Future for Task<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A task that returns `Option<T>` instead of panicking when cancelled.
|
||||
#[must_use]
|
||||
pub struct FallibleTask<T>(FallibleTaskState<T>);
|
||||
|
||||
enum FallibleTaskState<T> {
|
||||
/// A task that is ready to return a value
|
||||
Ready(Option<T>),
|
||||
|
||||
/// A task that is currently running (wraps async_task::FallibleTask).
|
||||
Spawned(async_task::FallibleTask<T, RunnableMeta>),
|
||||
}
|
||||
|
||||
impl<T> FallibleTask<T> {
|
||||
/// Creates a new fallible task that will resolve with the value.
|
||||
pub fn ready(val: T) -> Self {
|
||||
FallibleTask(FallibleTaskState::Ready(Some(val)))
|
||||
}
|
||||
|
||||
/// Detaching a task runs it to completion in the background.
|
||||
pub fn detach(self) {
|
||||
match self.0 {
|
||||
FallibleTaskState::Ready(_) => {}
|
||||
FallibleTaskState::Spawned(task) => task.detach(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Future for FallibleTask<T> {
|
||||
type Output = Option<T>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
||||
match unsafe { self.get_unchecked_mut() } {
|
||||
FallibleTask(FallibleTaskState::Ready(val)) => Poll::Ready(val.take()),
|
||||
FallibleTask(FallibleTaskState::Spawned(task)) => Pin::new(task).poll(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for FallibleTask<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.0 {
|
||||
FallibleTaskState::Ready(_) => f.debug_tuple("FallibleTask::Ready").finish(),
|
||||
FallibleTaskState::Spawned(task) => {
|
||||
f.debug_tuple("FallibleTask::Spawned").field(task).finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A task label is an opaque identifier that you can use to
|
||||
/// refer to a task in tests.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
@@ -252,7 +325,10 @@ impl BackgroundExecutor {
|
||||
|
||||
let (runnable, task) = unsafe {
|
||||
async_task::Builder::new()
|
||||
.metadata(RunnableMeta { location })
|
||||
.metadata(RunnableMeta {
|
||||
location,
|
||||
app: None,
|
||||
})
|
||||
.spawn_unchecked(
|
||||
move |_| async {
|
||||
let _notify_guard = NotifyOnDrop(pair);
|
||||
@@ -330,7 +406,10 @@ impl BackgroundExecutor {
|
||||
);
|
||||
|
||||
async_task::Builder::new()
|
||||
.metadata(RunnableMeta { location })
|
||||
.metadata(RunnableMeta {
|
||||
location,
|
||||
app: None,
|
||||
})
|
||||
.spawn(
|
||||
move |_| future,
|
||||
move |runnable| {
|
||||
@@ -340,7 +419,10 @@ impl BackgroundExecutor {
|
||||
} else {
|
||||
let location = core::panic::Location::caller();
|
||||
async_task::Builder::new()
|
||||
.metadata(RunnableMeta { location })
|
||||
.metadata(RunnableMeta {
|
||||
location,
|
||||
app: None,
|
||||
})
|
||||
.spawn(
|
||||
move |_| future,
|
||||
move |runnable| {
|
||||
@@ -566,7 +648,10 @@ impl BackgroundExecutor {
|
||||
}
|
||||
let location = core::panic::Location::caller();
|
||||
let (runnable, task) = async_task::Builder::new()
|
||||
.metadata(RunnableMeta { location })
|
||||
.metadata(RunnableMeta {
|
||||
location,
|
||||
app: None,
|
||||
})
|
||||
.spawn(move |_| async move {}, {
|
||||
let dispatcher = self.dispatcher.clone();
|
||||
move |runnable| dispatcher.dispatch_after(duration, RunnableVariant::Meta(runnable))
|
||||
@@ -681,7 +766,7 @@ impl ForegroundExecutor {
|
||||
where
|
||||
R: 'static,
|
||||
{
|
||||
self.spawn_with_priority(Priority::default(), future)
|
||||
self.inner_spawn(None, Priority::default(), future)
|
||||
}
|
||||
|
||||
/// Enqueues the given Task to run on the main thread at some point in the future.
|
||||
@@ -691,6 +776,31 @@ impl ForegroundExecutor {
|
||||
priority: Priority,
|
||||
future: impl Future<Output = R> + 'static,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
{
|
||||
self.inner_spawn(None, priority, future)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub(crate) fn spawn_context<R>(
|
||||
&self,
|
||||
app: std::sync::Weak<()>,
|
||||
future: impl Future<Output = R> + 'static,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
{
|
||||
self.inner_spawn(Some(app), Priority::default(), future)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub(crate) fn inner_spawn<R>(
|
||||
&self,
|
||||
app: Option<std::sync::Weak<()>>,
|
||||
priority: Priority,
|
||||
future: impl Future<Output = R> + 'static,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
{
|
||||
@@ -702,6 +812,7 @@ impl ForegroundExecutor {
|
||||
dispatcher: Arc<dyn PlatformDispatcher>,
|
||||
future: AnyLocalFuture<R>,
|
||||
location: &'static core::panic::Location<'static>,
|
||||
app: Option<std::sync::Weak<()>>,
|
||||
priority: Priority,
|
||||
) -> Task<R> {
|
||||
let (runnable, task) = spawn_local_with_source_location(
|
||||
@@ -709,12 +820,12 @@ impl ForegroundExecutor {
|
||||
move |runnable| {
|
||||
dispatcher.dispatch_on_main_thread(RunnableVariant::Meta(runnable), priority)
|
||||
},
|
||||
RunnableMeta { location },
|
||||
RunnableMeta { location, app },
|
||||
);
|
||||
runnable.schedule();
|
||||
Task(TaskState::Spawned(task))
|
||||
}
|
||||
inner::<R>(dispatcher, Box::pin(future), location, priority)
|
||||
inner::<R>(dispatcher, Box::pin(future), location, app, priority)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -847,3 +958,259 @@ impl Drop for Scope<'_> {
|
||||
self.executor.block(self.rx.next());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::{App, TestDispatcher, TestPlatform};
|
||||
use rand::SeedableRng;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn sanity_test_tasks_run() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor, foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let liveness_token = std::sync::Arc::downgrade(&app.borrow().liveness);
|
||||
|
||||
let task_ran = Rc::new(RefCell::new(false));
|
||||
|
||||
foreground_executor
|
||||
.spawn_context(liveness_token, {
|
||||
let task_ran = Rc::clone(&task_ran);
|
||||
async move {
|
||||
*task_ran.borrow_mut() = true;
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Run dispatcher while app is still alive
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
// Task should have run
|
||||
assert!(
|
||||
*task_ran.borrow(),
|
||||
"Task should run normally when app is alive"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_task_cancelled_when_app_dropped() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor, foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let liveness_token = std::sync::Arc::downgrade(&app.borrow().liveness);
|
||||
let app_weak = Rc::downgrade(&app);
|
||||
|
||||
let task_ran = Rc::new(RefCell::new(false));
|
||||
let task_ran_clone = Rc::clone(&task_ran);
|
||||
|
||||
foreground_executor
|
||||
.spawn_context(liveness_token, async move {
|
||||
*task_ran_clone.borrow_mut() = true;
|
||||
})
|
||||
.detach();
|
||||
|
||||
drop(app);
|
||||
|
||||
assert!(app_weak.upgrade().is_none(), "App should have been dropped");
|
||||
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
// The task should have been cancelled, not run
|
||||
assert!(
|
||||
!*task_ran.borrow(),
|
||||
"Task should have been cancelled when app was dropped, but it ran!"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_tasks_both_cancel() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor, foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let liveness_token = std::sync::Arc::downgrade(&app.borrow().liveness);
|
||||
let app_weak = Rc::downgrade(&app);
|
||||
|
||||
let outer_completed = Rc::new(RefCell::new(false));
|
||||
let inner_completed = Rc::new(RefCell::new(false));
|
||||
let reached_await = Rc::new(RefCell::new(false));
|
||||
|
||||
let outer_flag = Rc::clone(&outer_completed);
|
||||
let inner_flag = Rc::clone(&inner_completed);
|
||||
let await_flag = Rc::clone(&reached_await);
|
||||
|
||||
// Channel to block the inner task until we're ready
|
||||
let (tx, rx) = futures::channel::oneshot::channel::<()>();
|
||||
|
||||
// We need clones of executor and liveness_token for the inner spawn
|
||||
let inner_executor = foreground_executor.clone();
|
||||
let inner_liveness_token = liveness_token.clone();
|
||||
|
||||
foreground_executor
|
||||
.spawn_context(liveness_token, async move {
|
||||
let inner_task = inner_executor.spawn_context(inner_liveness_token, {
|
||||
let inner_flag = Rc::clone(&inner_flag);
|
||||
async move {
|
||||
rx.await.ok();
|
||||
*inner_flag.borrow_mut() = true;
|
||||
}
|
||||
});
|
||||
|
||||
*await_flag.borrow_mut() = true;
|
||||
|
||||
inner_task.await;
|
||||
|
||||
*outer_flag.borrow_mut() = true;
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Run dispatcher until outer task reaches the await point
|
||||
// The inner task will be blocked on the channel
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
// Verify we actually reached the await point before dropping the app
|
||||
assert!(
|
||||
*reached_await.borrow(),
|
||||
"Outer task should have reached the await point"
|
||||
);
|
||||
|
||||
// Neither task should have completed yet
|
||||
assert!(
|
||||
!*outer_completed.borrow(),
|
||||
"Outer task should not have completed yet"
|
||||
);
|
||||
assert!(
|
||||
!*inner_completed.borrow(),
|
||||
"Inner task should not have completed yet"
|
||||
);
|
||||
|
||||
// Drop the channel sender and app while outer is awaiting inner
|
||||
drop(tx);
|
||||
drop(app);
|
||||
assert!(app_weak.upgrade().is_none(), "App should have been dropped");
|
||||
|
||||
// Run dispatcher - both tasks should be cancelled
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
// Neither task should have completed (both were cancelled)
|
||||
assert!(
|
||||
!*outer_completed.borrow(),
|
||||
"Outer task should have been cancelled, not completed"
|
||||
);
|
||||
assert!(
|
||||
!*inner_completed.borrow(),
|
||||
"Inner task should have been cancelled, not completed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_task_without_app_tracking_still_runs() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor, foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let app_weak = Rc::downgrade(&app);
|
||||
|
||||
let task_ran = Rc::new(RefCell::new(false));
|
||||
let task_ran_clone = Rc::clone(&task_ran);
|
||||
|
||||
let _task = foreground_executor.spawn(async move {
|
||||
*task_ran_clone.borrow_mut() = true;
|
||||
});
|
||||
|
||||
drop(app);
|
||||
|
||||
assert!(app_weak.upgrade().is_none(), "App should have been dropped");
|
||||
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
assert!(
|
||||
*task_ran.borrow(),
|
||||
"Task without app tracking should still run after app is dropped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_polling_cancelled_task_panics() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let liveness_token = std::sync::Arc::downgrade(&app.borrow().liveness);
|
||||
let app_weak = Rc::downgrade(&app);
|
||||
|
||||
let task = foreground_executor.spawn_context(liveness_token, async move { 42 });
|
||||
|
||||
drop(app);
|
||||
|
||||
assert!(app_weak.upgrade().is_none(), "App should have been dropped");
|
||||
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
background_executor.block(task);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_polling_cancelled_task_returns_none_with_fallible() {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
|
||||
let arc_dispatcher = Arc::new(dispatcher.clone());
|
||||
let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
|
||||
|
||||
let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
|
||||
let asset_source = Arc::new(());
|
||||
let http_client = http_client::FakeHttpClient::with_404_response();
|
||||
|
||||
let app = App::new_app(platform, asset_source, http_client);
|
||||
let liveness_token = std::sync::Arc::downgrade(&app.borrow().liveness);
|
||||
let app_weak = Rc::downgrade(&app);
|
||||
|
||||
let task = foreground_executor
|
||||
.spawn_context(liveness_token, async move { 42 })
|
||||
.fallible();
|
||||
|
||||
drop(app);
|
||||
|
||||
assert!(app_weak.upgrade().is_none(), "App should have been dropped");
|
||||
|
||||
dispatcher.run_until_parked();
|
||||
|
||||
let result = background_executor.block(task);
|
||||
assert_eq!(result, None, "Cancelled task should return None");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,23 +118,16 @@ pub use window::*;
|
||||
/// The context trait, allows the different contexts in GPUI to be used
|
||||
/// interchangeably for certain operations.
|
||||
pub trait AppContext {
|
||||
/// The result type for this context, used for async contexts that
|
||||
/// can't hold a direct reference to the application context.
|
||||
type Result<T>;
|
||||
|
||||
/// Create a new entity in the app context.
|
||||
#[expect(
|
||||
clippy::wrong_self_convention,
|
||||
reason = "`App::new` is an ubiquitous function for creating entities"
|
||||
)]
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T>;
|
||||
|
||||
/// Reserve a slot for a entity to be inserted later.
|
||||
/// The returned [Reservation] allows you to obtain the [EntityId] for the future entity.
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>>;
|
||||
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>;
|
||||
|
||||
/// Insert a new entity in the app context based on a [Reservation] previously obtained from [`reserve_entity`].
|
||||
///
|
||||
@@ -143,28 +136,24 @@ pub trait AppContext {
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_entity: impl FnOnce(&mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
) -> Entity<T>;
|
||||
|
||||
/// Update a entity in the app context.
|
||||
fn update_entity<T, R>(
|
||||
&mut self,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R>
|
||||
) -> R
|
||||
where
|
||||
T: 'static;
|
||||
|
||||
/// Update a entity in the app context.
|
||||
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> Self::Result<GpuiBorrow<'a, T>>
|
||||
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
|
||||
where
|
||||
T: 'static;
|
||||
|
||||
/// Read a entity from the app context.
|
||||
fn read_entity<T, R>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
|
||||
where
|
||||
T: 'static;
|
||||
|
||||
@@ -188,7 +177,7 @@ pub trait AppContext {
|
||||
R: Send + 'static;
|
||||
|
||||
/// Read a global from this app context
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
|
||||
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
|
||||
where
|
||||
G: Global;
|
||||
}
|
||||
@@ -215,24 +204,24 @@ pub trait VisualContext: AppContext {
|
||||
&mut self,
|
||||
entity: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R>;
|
||||
) -> Result<R>;
|
||||
|
||||
/// Create a new entity, with access to `Window`.
|
||||
fn new_window_entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
) -> Result<Entity<T>>;
|
||||
|
||||
/// Replace the root view of a window with a new view.
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
) -> Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render;
|
||||
|
||||
/// Focus a entity in the window, if it implements the [`Focusable`] trait.
|
||||
fn focus<V>(&mut self, entity: &Entity<V>) -> Self::Result<()>
|
||||
fn focus<V>(&mut self, entity: &Entity<V>) -> Result<()>
|
||||
where
|
||||
V: Focusable;
|
||||
}
|
||||
@@ -284,24 +273,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// A flatten equivalent for anyhow `Result`s.
|
||||
pub trait Flatten<T> {
|
||||
/// Convert this type into a simple `Result<T>`.
|
||||
fn flatten(self) -> Result<T>;
|
||||
}
|
||||
|
||||
impl<T> Flatten<T> for Result<Result<T>> {
|
||||
fn flatten(self) -> Result<T> {
|
||||
self?
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Flatten<T> for Result<T> {
|
||||
fn flatten(self) -> Result<T> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Information about the GPU GPUI is running on.
|
||||
#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
|
||||
pub struct GpuSpecs {
|
||||
|
||||
@@ -575,10 +575,30 @@ pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
|
||||
/// This type is public so that our test macro can generate and use it, but it should not
|
||||
/// be considered part of our public API.
|
||||
#[doc(hidden)]
|
||||
#[derive(Debug)]
|
||||
pub struct RunnableMeta {
|
||||
/// Location of the runnable
|
||||
pub location: &'static core::panic::Location<'static>,
|
||||
/// Weak reference to check if the app is still alive before running this task
|
||||
pub app: Option<std::sync::Weak<()>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RunnableMeta {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RunnableMeta")
|
||||
.field("location", &self.location)
|
||||
.field("app_alive", &self.is_app_alive())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl RunnableMeta {
|
||||
/// Returns true if the app is still alive (or if no app tracking is configured).
|
||||
pub fn is_app_alive(&self) -> bool {
|
||||
match &self.app {
|
||||
Some(weak) => weak.strong_count() > 0,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::{Action, App, Platform, SharedString};
|
||||
use util::ResultExt;
|
||||
|
||||
/// A menu of the application, either a main menu or a submenu
|
||||
pub struct Menu {
|
||||
@@ -263,14 +262,18 @@ pub(crate) fn init_app_menus(platform: &dyn Platform, cx: &App) {
|
||||
platform.on_will_open_app_menu(Box::new({
|
||||
let cx = cx.to_async();
|
||||
move || {
|
||||
cx.update(|cx| cx.clear_pending_keystrokes()).ok();
|
||||
if let Some(app) = cx.app.upgrade() {
|
||||
app.borrow_mut().update(|cx| cx.clear_pending_keystrokes());
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
platform.on_validate_app_menu_command(Box::new({
|
||||
let cx = cx.to_async();
|
||||
move |action| {
|
||||
cx.update(|cx| cx.is_action_available(action))
|
||||
cx.app
|
||||
.upgrade()
|
||||
.map(|app| app.borrow_mut().update(|cx| cx.is_action_available(action)))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}));
|
||||
@@ -278,7 +281,9 @@ pub(crate) fn init_app_menus(platform: &dyn Platform, cx: &App) {
|
||||
platform.on_app_menu_action(Box::new({
|
||||
let cx = cx.to_async();
|
||||
move |action| {
|
||||
cx.update(|cx| cx.dispatch_action(action)).log_err();
|
||||
if let Some(app) = cx.app.upgrade() {
|
||||
app.borrow_mut().update(|cx| cx.dispatch_action(action));
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -32,7 +32,11 @@ impl HeadlessClient {
|
||||
.insert_source(main_receiver, |event, _, _: &mut HeadlessClient| {
|
||||
if let calloop::channel::Event::Msg(runnable) = event {
|
||||
match runnable {
|
||||
crate::RunnableVariant::Meta(runnable) => runnable.run(),
|
||||
crate::RunnableVariant::Meta(runnable) => {
|
||||
if runnable.metadata().is_app_alive() {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
crate::RunnableVariant::Compat(runnable) => runnable.run(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -502,7 +502,14 @@ impl WaylandClient {
|
||||
let start = Instant::now();
|
||||
let mut timing = match runnable {
|
||||
RunnableVariant::Meta(runnable) => {
|
||||
let location = runnable.metadata().location;
|
||||
let metadata = runnable.metadata();
|
||||
let location = metadata.location;
|
||||
|
||||
if !metadata.is_app_alive() {
|
||||
drop(runnable);
|
||||
return;
|
||||
}
|
||||
|
||||
let timing = TaskTiming {
|
||||
location,
|
||||
start,
|
||||
|
||||
@@ -316,7 +316,14 @@ impl X11Client {
|
||||
let start = Instant::now();
|
||||
let mut timing = match runnable {
|
||||
RunnableVariant::Meta(runnable) => {
|
||||
let location = runnable.metadata().location;
|
||||
let metadata = runnable.metadata();
|
||||
let location = metadata.location;
|
||||
|
||||
if !metadata.is_app_alive() {
|
||||
drop(runnable);
|
||||
return;
|
||||
}
|
||||
|
||||
let timing = TaskTiming {
|
||||
location,
|
||||
start,
|
||||
|
||||
@@ -251,7 +251,13 @@ extern "C" fn trampoline(runnable: *mut c_void) {
|
||||
let task =
|
||||
unsafe { Runnable::<RunnableMeta>::from_raw(NonNull::new_unchecked(runnable as *mut ())) };
|
||||
|
||||
let location = task.metadata().location;
|
||||
let metadata = task.metadata();
|
||||
let location = metadata.location;
|
||||
|
||||
if !metadata.is_app_alive() {
|
||||
drop(task);
|
||||
return;
|
||||
}
|
||||
|
||||
let start = Instant::now();
|
||||
let timing = TaskTiming {
|
||||
|
||||
@@ -687,7 +687,7 @@ impl Platform for MacPlatform {
|
||||
}
|
||||
|
||||
self.background_executor()
|
||||
.spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
|
||||
.spawn(async { done_rx.await.map_err(|e| anyhow!(e))? })
|
||||
}
|
||||
|
||||
fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
|
||||
|
||||
@@ -177,7 +177,14 @@ impl TestDispatcher {
|
||||
|
||||
// todo(localcc): add timings to tests
|
||||
match runnable {
|
||||
RunnableVariant::Meta(runnable) => runnable.run(),
|
||||
RunnableVariant::Meta(runnable) => {
|
||||
if !runnable.metadata().is_app_alive() {
|
||||
drop(runnable);
|
||||
self.state.lock().is_main_thread = was_main_thread;
|
||||
return true;
|
||||
}
|
||||
runnable.run()
|
||||
}
|
||||
RunnableVariant::Compat(runnable) => runnable.run(),
|
||||
};
|
||||
|
||||
|
||||
@@ -73,7 +73,14 @@ impl WindowsDispatcher {
|
||||
|
||||
let mut timing = match runnable {
|
||||
RunnableVariant::Meta(runnable) => {
|
||||
let location = runnable.metadata().location;
|
||||
let metadata = runnable.metadata();
|
||||
let location = metadata.location;
|
||||
|
||||
if !metadata.is_app_alive() {
|
||||
drop(runnable);
|
||||
return;
|
||||
}
|
||||
|
||||
let timing = TaskTiming {
|
||||
location,
|
||||
start,
|
||||
|
||||
@@ -4909,11 +4909,11 @@ impl<V: 'static + Render> WindowHandle<V> {
|
||||
where
|
||||
C: AppContext,
|
||||
{
|
||||
crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
|
||||
cx.update_window(self.any_handle, |root_view, _, _| {
|
||||
root_view
|
||||
.downcast::<V>()
|
||||
.map_err(|_| anyhow!("the type of the window's root view has changed"))
|
||||
}))
|
||||
})?
|
||||
}
|
||||
|
||||
/// Updates the root view of this window.
|
||||
|
||||
Reference in New Issue
Block a user