@@ -7,6 +7,9 @@ use anyhow::{anyhow, Context as _};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use std::{future::Future, rc::Weak};
|
||||
|
||||
/// An async-friendly version of [AppContext] with a static lifetime so it can be held across `await` points in async code.
|
||||
/// You're provided with an instance when calling [AppContext::spawn], and you can also create one with [AppContext::to_async].
|
||||
/// Internally, this holds a weak reference to an `AppContext`, so its methods are fallible to protect against cases where the [AppContext] is dropped.
|
||||
#[derive(Clone)]
|
||||
pub struct AsyncAppContext {
|
||||
pub(crate) app: Weak<AppCell>,
|
||||
@@ -139,6 +142,8 @@ impl AsyncAppContext {
|
||||
self.foreground_executor.spawn(f(self.clone()))
|
||||
}
|
||||
|
||||
/// Determine whether global state of the specified type has been assigned.
|
||||
/// Returns an error if the `AppContext` has been dropped.
|
||||
pub fn has_global<G: 'static>(&self) -> Result<bool> {
|
||||
let app = self
|
||||
.app
|
||||
@@ -148,6 +153,9 @@ impl AsyncAppContext {
|
||||
Ok(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 `AppContext` has been dropped.
|
||||
pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
|
||||
let app = self
|
||||
.app
|
||||
@@ -157,6 +165,9 @@ impl AsyncAppContext {
|
||||
Ok(read(app.global(), &app))
|
||||
}
|
||||
|
||||
/// Reads the global state of the specified type, passing it to the given callback.
|
||||
/// Similar to [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 `AppContext` has been dropped.
|
||||
pub fn try_read_global<G: 'static, R>(
|
||||
&self,
|
||||
read: impl FnOnce(&G, &AppContext) -> R,
|
||||
@@ -166,6 +177,8 @@ impl AsyncAppContext {
|
||||
Some(read(app.try_global()?, &app))
|
||||
}
|
||||
|
||||
/// A convenience method for [AppContext::update_global]
|
||||
/// for updating the global state of the specified type.
|
||||
pub fn update_global<G: 'static, R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut G, &mut AppContext) -> R,
|
||||
@@ -179,6 +192,8 @@ impl AsyncAppContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
@@ -188,14 +203,16 @@ pub struct AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl AsyncWindowContext {
|
||||
pub fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
}
|
||||
|
||||
pub(crate) fn new(app: AsyncAppContext, 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 [WindowContext::update()]
|
||||
pub fn update<R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
|
||||
@@ -203,10 +220,12 @@ impl AsyncWindowContext {
|
||||
self.app.update_window(self.window, update)
|
||||
}
|
||||
|
||||
/// A convenience method for [WindowContext::on_next_frame()]
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
|
||||
self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
|
||||
}
|
||||
|
||||
/// A convenience method for [AppContext::global()]
|
||||
pub fn read_global<G: 'static, R>(
|
||||
&mut self,
|
||||
read: impl FnOnce(&G, &WindowContext) -> R,
|
||||
@@ -214,6 +233,8 @@ impl AsyncWindowContext {
|
||||
self.window.update(self, |_, cx| read(cx.global(), cx))
|
||||
}
|
||||
|
||||
/// A convenience method for [AppContext::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 WindowContext) -> R,
|
||||
@@ -224,6 +245,8 @@ impl AsyncWindowContext {
|
||||
self.window.update(self, |_, cx| cx.update_global(update))
|
||||
}
|
||||
|
||||
/// Schedule a future to be executed on the main thread. This is used for collecting
|
||||
/// the results of background tasks and updating the UI.
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
|
||||
where
|
||||
Fut: Future<Output = R> + 'static,
|
||||
|
||||
@@ -31,6 +31,7 @@ impl From<u64> for EntityId {
|
||||
}
|
||||
|
||||
impl EntityId {
|
||||
/// Converts this entity id to a [u64]
|
||||
pub fn as_u64(self) -> u64 {
|
||||
self.0.as_ffi()
|
||||
}
|
||||
@@ -140,7 +141,7 @@ impl EntityMap {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Lease<'a, T> {
|
||||
pub(crate) struct Lease<'a, T> {
|
||||
entity: Option<Box<dyn Any>>,
|
||||
pub model: &'a Model<T>,
|
||||
entity_type: PhantomData<T>,
|
||||
@@ -169,8 +170,9 @@ impl<'a, T> Drop for Lease<'a, T> {
|
||||
}
|
||||
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct Slot<T>(Model<T>);
|
||||
pub(crate) struct Slot<T>(Model<T>);
|
||||
|
||||
/// A dynamically typed reference to a model, which can be downcast into a `Model<T>`.
|
||||
pub struct AnyModel {
|
||||
pub(crate) entity_id: EntityId,
|
||||
pub(crate) entity_type: TypeId,
|
||||
@@ -195,14 +197,17 @@ impl AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the id associated with this model.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.entity_id
|
||||
}
|
||||
|
||||
/// Returns the [TypeId] associated with this model.
|
||||
pub fn entity_type(&self) -> TypeId {
|
||||
self.entity_type
|
||||
}
|
||||
|
||||
/// Converts this model handle into a weak variant, which does not prevent it from being released.
|
||||
pub fn downgrade(&self) -> AnyWeakModel {
|
||||
AnyWeakModel {
|
||||
entity_id: self.entity_id,
|
||||
@@ -211,6 +216,8 @@ impl AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this model handle into a strongly-typed model handle of the given type.
|
||||
/// If this model handle is not of the specified type, returns itself as an error variant.
|
||||
pub fn downcast<T: 'static>(self) -> Result<Model<T>, AnyModel> {
|
||||
if TypeId::of::<T>() == self.entity_type {
|
||||
Ok(Model {
|
||||
@@ -307,6 +314,8 @@ impl std::fmt::Debug for AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// A strong, well typed reference to a struct which is managed
|
||||
/// by GPUI
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct Model<T> {
|
||||
#[deref]
|
||||
@@ -368,10 +377,12 @@ impl<T: 'static> Model<T> {
|
||||
self.any_model
|
||||
}
|
||||
|
||||
/// Grab a reference to this entity from the context.
|
||||
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
|
||||
cx.entities.read(self)
|
||||
}
|
||||
|
||||
/// Read the entity referenced by this model with the given function.
|
||||
pub fn read_with<R, C: Context>(
|
||||
&self,
|
||||
cx: &C,
|
||||
@@ -437,6 +448,7 @@ impl<T> PartialEq<WeakModel<T>> for Model<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type erased, weak reference to a model.
|
||||
#[derive(Clone)]
|
||||
pub struct AnyWeakModel {
|
||||
pub(crate) entity_id: EntityId,
|
||||
@@ -445,10 +457,12 @@ pub struct AnyWeakModel {
|
||||
}
|
||||
|
||||
impl AnyWeakModel {
|
||||
/// Get the entity ID associated with this weak reference.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.entity_id
|
||||
}
|
||||
|
||||
/// Check if this weak handle can be upgraded, or if the model has already been dropped
|
||||
pub fn is_upgradable(&self) -> bool {
|
||||
let ref_count = self
|
||||
.entity_ref_counts
|
||||
@@ -458,6 +472,7 @@ impl AnyWeakModel {
|
||||
ref_count > 0
|
||||
}
|
||||
|
||||
/// Upgrade this weak model reference to a strong reference.
|
||||
pub fn upgrade(&self) -> Option<AnyModel> {
|
||||
let ref_counts = &self.entity_ref_counts.upgrade()?;
|
||||
let ref_counts = ref_counts.read();
|
||||
@@ -485,6 +500,7 @@ impl AnyWeakModel {
|
||||
})
|
||||
}
|
||||
|
||||
/// Assert that model referenced by this weak handle has been dropped.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn assert_dropped(&self) {
|
||||
self.entity_ref_counts
|
||||
@@ -527,6 +543,7 @@ impl PartialEq for AnyWeakModel {
|
||||
|
||||
impl Eq for AnyWeakModel {}
|
||||
|
||||
/// A weak reference to a model of the given type.
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct WeakModel<T> {
|
||||
#[deref]
|
||||
@@ -617,12 +634,12 @@ lazy_static::lazy_static! {
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
|
||||
pub struct HandleId {
|
||||
pub(crate) struct HandleId {
|
||||
id: u64, // id of the handle itself, not the pointed at object
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub struct LeakDetector {
|
||||
pub(crate) struct LeakDetector {
|
||||
next_handle_id: u64,
|
||||
entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::{
|
||||
future::Future,
|
||||
};
|
||||
|
||||
/// The app context, with specialized behavior for the given model.
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct ModelContext<'a, T> {
|
||||
#[deref]
|
||||
@@ -24,20 +25,24 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
Self { app, model_state }
|
||||
}
|
||||
|
||||
/// The entity id of the model backing this context.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.model_state.entity_id
|
||||
}
|
||||
|
||||
/// Returns a handle to the model belonging to this context.
|
||||
pub fn handle(&self) -> Model<T> {
|
||||
self.weak_model()
|
||||
.upgrade()
|
||||
.expect("The entity must be alive if we have a model context")
|
||||
}
|
||||
|
||||
/// Returns a weak handle to the model belonging to this context.
|
||||
pub fn weak_model(&self) -> WeakModel<T> {
|
||||
self.model_state.clone()
|
||||
}
|
||||
|
||||
/// Arranges for the given function to be called whenever [ModelContext::notify] or [ViewContext::notify] is called with the given model or view.
|
||||
pub fn observe<W, E>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
@@ -59,6 +64,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Subscribe to an event type from another model or view
|
||||
pub fn subscribe<T2, E, Evt>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
@@ -81,6 +87,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when GPUI releases this model.
|
||||
pub fn on_release(
|
||||
&mut self,
|
||||
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||
@@ -99,6 +106,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be run on the release of another model or view
|
||||
pub fn observe_release<T2, E>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
@@ -124,6 +132,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
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 ModelContext<'_, T>) + 'static,
|
||||
@@ -140,6 +149,8 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
subscription
|
||||
}
|
||||
|
||||
/// 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 [gpui::SHUTDOWN_TIMEOUT] until the app fully quits.
|
||||
pub fn on_app_quit<Fut>(
|
||||
&mut self,
|
||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + 'static,
|
||||
@@ -165,6 +176,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Tell GPUI that this model has changed and observers of it should be notified.
|
||||
pub fn notify(&mut self) {
|
||||
if self
|
||||
.app
|
||||
@@ -177,6 +189,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the given global
|
||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||
where
|
||||
G: 'static,
|
||||
@@ -187,6 +200,9 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Spawn the future returned by the given function.
|
||||
/// The function is provided a weak handle to the model owned by this context and a context that can be held across await points.
|
||||
/// The returned task must be held or detached.
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(WeakModel<T>, AsyncAppContext) -> Fut) -> Task<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -199,6 +215,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
|
||||
impl<'a, T> ModelContext<'a, 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>,
|
||||
|
||||
Reference in New Issue
Block a user