Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Replace shared asset futures with owning cache entries (#63934)

Lukas Wirth5896274168e0
diff --git a/crates/cloud_api_client/Cargo.toml b/crates/cloud_api_client/Cargo.toml
index 4f8322063bc..1b65a1491e9 100644
--- a/crates/cloud_api_client/Cargo.toml
+++ b/crates/cloud_api_client/Cargo.toml
@@ -21,9 +21,15 @@ http_client.workspace = true
parking_lot.workspace = true
serde.workspace = true
serde_json.workspace = true
-async-lock.workspace = true
thiserror.workspace = true
yawc.workspace = true
+[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+# Workspace inheritance would re-enable defaults, including blocking synchronization.
+async-lock = { version = "3.4.2", default-features = false }
+
+[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies]
+async-lock.workspace = true
+
[target.'cfg(not(target_family = "wasm"))'.dependencies]
gpui_tokio.workspace = true
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index 336e3c00357..8797066d2c0 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -89,7 +89,6 @@ serde.workspace = true
serde_json.workspace = true
slotmap.workspace = true
smallvec.workspace = true
-async-channel.workspace = true
stacksafe = { workspace = true, optional = true }
strum.workspace = true
sum_tree.workspace = true
@@ -109,6 +108,13 @@ web-time.workspace = true
heapless.workspace = true
ztracing.workspace = true
+[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+# Workspace inheritance would re-enable defaults, including blocking channel synchronization.
+async-channel = { version = "2.5.0", default-features = false }
+
+[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies]
+async-channel.workspace = true
+
[target.'cfg(target_family = "wasm")'.dependencies]
getrandom = { version = "0.3.4", features = ["wasm_js"] }
uuid = { workspace = true, features = ["js"] }
diff --git a/crates/gpui/examples/image_gallery.rs b/crates/gpui/examples/image_gallery.rs
index 16b9b17a3f1..d1cb919698f 100644
--- a/crates/gpui/examples/image_gallery.rs
+++ b/crates/gpui/examples/image_gallery.rs
@@ -3,12 +3,11 @@
#[path = "example_support/fonts.rs"]
mod example_support;
-use futures::FutureExt;
use gpui::{
- App, AppContext, Asset as _, AssetLogger, Bounds, ClickEvent, Context, ElementId, Entity,
- ImageAssetLoader, ImageCache, ImageCacheProvider, KeyBinding, Menu, MenuItem,
- RetainAllImageCache, SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions,
- actions, div, hash, image_cache, img, prelude::*, px, rgb, size,
+ App, AppContext, Bounds, ClickEvent, Context, ElementId, Entity, ImageCache,
+ ImageCacheProvider, KeyBinding, Menu, MenuItem, RetainAllImageCache, SharedString,
+ TitlebarOptions, Window, WindowBounds, WindowOptions, actions, div, hash, image_cache, img,
+ prelude::*, px, rgb, size,
};
#[cfg(not(target_family = "wasm"))]
use reqwest_client::ReqwestClient;
@@ -176,7 +175,7 @@ struct SimpleLruCache {
impl SimpleLruCache {
fn new(max_items: usize, cx: &mut Context<Self>) -> Self {
cx.on_release(|simple_cache, cx| {
- for (_, mut item) in std::mem::take(&mut simple_cache.cache) {
+ for (_, item) in std::mem::take(&mut simple_cache.cache) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, None);
}
@@ -213,14 +212,12 @@ impl ImageCache for SimpleLruCache {
self.usages.remove(current_ix);
self.usages.insert(0, hash);
- return item.get();
+ return item.use_image(window);
}
- let fut = AssetLogger::<ImageAssetLoader>::load(resource.clone(), cx);
- let task = cx.background_executor().spawn(fut).shared();
if self.usages.len() == self.max_items {
let oldest = self.usages.pop().unwrap();
- let mut image = self
+ let image = self
.cache
.remove(&oldest)
.expect("cache and usages must be in sync");
@@ -228,23 +225,12 @@ impl ImageCache for SimpleLruCache {
cx.drop_image(image, Some(window));
}
}
- self.cache
- .insert(hash, gpui::ImageCacheItem::Loading(task.clone()));
+ let item = gpui::ImageCacheItem::new(resource, cx);
+ let result = item.use_image(window);
+ self.cache.insert(hash, item);
self.usages.insert(0, hash);
- let entity = window.current_view();
- window
- .spawn(cx, {
- async move |cx| {
- _ = task.await;
- cx.on_next_frame(move |_, cx| {
- cx.notify(entity);
- });
- }
- })
- .detach();
-
- None
+ result
}
}
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 9811fc376a8..668b8c9f5c2 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -14,11 +14,7 @@ use std::{
use anyhow::{Context as _, Result, anyhow};
use derive_more::{Deref, DerefMut};
-use futures::{
- Future, FutureExt,
- channel::oneshot,
- future::{LocalBoxFuture, Shared},
-};
+use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
use itertools::Itertools;
use parking_lot::RwLock;
use slotmap::SlotMap;
@@ -43,6 +39,7 @@ pub use visual_test_context::*;
#[cfg(any(feature = "inspector", debug_assertions))]
use crate::InspectorElementRegistry;
+use crate::asset_cache::CachedLoad;
use crate::{
Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError,
@@ -2656,27 +2653,25 @@ impl App {
self.loading_assets.contains_key(&asset_id)
}
- /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
+ /// Starts loading an uncached asset and returns its result once available.
///
- /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
- /// time, and the results of this call will be cached
- pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
- let asset_id = (TypeId::of::<A>(), hash(source));
- let mut is_first = false;
- let task = self
- .loading_assets
- .remove(&asset_id)
- .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
- .unwrap_or_else(|| {
- is_first = true;
- let future = A::load(source.clone(), self);
-
- self.background_executor().spawn(future).shared()
- });
-
- self.loading_assets.insert(asset_id, Box::new(task.clone()));
+ /// Pending loads and completed results are cached until [`Self::remove_asset`].
+ /// This method does not subscribe a view to completion notifications.
+ pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
+ self.asset_entry::<A>(source).get()
+ }
- (task, is_first)
+ pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
+ let asset_id = (TypeId::of::<A>(), hash(source));
+ if !self.loading_assets.contains_key(&asset_id) {
+ let future = A::load(source.clone(), self);
+ let entry = CachedLoad::new(future, self);
+ self.loading_assets.insert(asset_id, Box::new(entry));
+ }
+ self.loading_assets
+ .get(&asset_id)
+ .and_then(|entry| entry.downcast_ref())
+ .expect("asset cache entries are keyed by their asset type")
}
/// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
diff --git a/crates/gpui/src/asset_cache.rs b/crates/gpui/src/asset_cache.rs
index bd1271541ab..4c7bee12076 100644
--- a/crates/gpui/src/asset_cache.rs
+++ b/crates/gpui/src/asset_cache.rs
@@ -1,12 +1,71 @@
-use crate::{App, SharedString, SharedUri};
+use crate::{App, EntityId, SharedString, SharedUri, Task};
+use collections::FxHashSet;
use futures::{Future, TryFutureExt};
+use std::cell::RefCell;
use std::fmt::Debug;
use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;
+use std::mem;
use std::path::{Path, PathBuf};
+use std::rc::Rc;
use std::sync::Arc;
+pub(crate) struct CachedLoad<T> {
+ state: Rc<RefCell<CachedLoadState<T>>>,
+ // Keep the owner outside the state so publishing a result cannot cancel its own task.
+ _task: Task<()>,
+}
+
+enum CachedLoadState<T> {
+ Loading(FxHashSet<EntityId>),
+ Loaded(T),
+}
+
+impl<T: Clone + Send + 'static> CachedLoad<T> {
+ pub(crate) fn new(future: impl Future<Output = T> + Send + 'static, cx: &App) -> Self {
+ let state = Rc::new(RefCell::new(CachedLoadState::Loading(FxHashSet::default())));
+ let task = cx.background_executor().spawn(future);
+ let task = cx.spawn({
+ let state = Rc::downgrade(&state);
+ async move |cx| {
+ let result = task.await;
+ let Some(state) = state.upgrade() else {
+ return;
+ };
+ let previous =
+ mem::replace(&mut *state.borrow_mut(), CachedLoadState::Loaded(result));
+ let CachedLoadState::Loading(views) = previous else {
+ unreachable!("a cached load completes only once");
+ };
+ cx.update(|cx| {
+ for view in views {
+ cx.notify(view);
+ }
+ });
+ }
+ });
+ Self { state, _task: task }
+ }
+
+ pub(crate) fn get(&self) -> Option<T> {
+ match &*self.state.borrow() {
+ CachedLoadState::Loading(_) => None,
+ CachedLoadState::Loaded(result) => Some(result.clone()),
+ }
+ }
+
+ pub(crate) fn use_by(&self, view: EntityId) -> Option<T> {
+ match &mut *self.state.borrow_mut() {
+ CachedLoadState::Loading(views) => {
+ views.insert(view);
+ None
+ }
+ CachedLoadState::Loaded(result) => Some(result.clone()),
+ }
+ }
+}
+
/// An enum representing
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum Resource {
@@ -80,3 +139,220 @@ where
pub fn hash<T: Hash>(data: &T) -> u64 {
collections::FxBuildHasher.hash_one(data)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{AppContext, TestAppContext};
+ use futures::channel::oneshot;
+ use std::{
+ cell::Cell,
+ collections::VecDeque,
+ hash::{Hash, Hasher},
+ rc::Rc,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
+ },
+ };
+
+ #[gpui::test]
+ fn cached_load_caches_success_and_error(cx: &mut TestAppContext) {
+ let successful_load =
+ cx.update(|cx| CachedLoad::new(async { Ok::<_, &'static str>(42) }, cx));
+ let failed_load =
+ cx.update(|cx| CachedLoad::new(async { Err::<i32, _>("load failed") }, cx));
+
+ assert_eq!(successful_load.get(), None);
+ assert_eq!(failed_load.get(), None);
+
+ cx.run_until_parked();
+
+ assert_eq!(successful_load.get(), Some(Ok(42)));
+ assert_eq!(successful_load.get(), Some(Ok(42)));
+ assert_eq!(failed_load.get(), Some(Err("load failed")));
+ assert_eq!(failed_load.get(), Some(Err("load failed")));
+ }
+
+ #[gpui::test]
+ fn completed_load_without_subscribers_is_cached_and_deduplicated(cx: &mut TestAppContext) {
+ let (sender, receiver) = oneshot::channel();
+ let source = TestAssetSource::new(1, [receiver]);
+
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+ assert_eq!(source.load_count(), 1);
+
+ assert!(sender.send(Ok(42)).is_ok());
+ cx.run_until_parked();
+
+ assert_eq!(
+ cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)),
+ Some(Ok(42))
+ );
+ assert_eq!(
+ cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)),
+ Some(Ok(42))
+ );
+ assert_eq!(source.load_count(), 1);
+ }
+
+ #[gpui::test]
+ fn load_completion_notifies_each_observing_entity_once(cx: &mut TestAppContext) {
+ let (sender, receiver) = oneshot::channel::<i32>();
+ let load = cx.update(|cx| {
+ CachedLoad::new(
+ async move { receiver.await.expect("test sends a result") },
+ cx,
+ )
+ });
+ let first_notification_count = Rc::new(Cell::new(0));
+ let second_notification_count = Rc::new(Cell::new(0));
+ let (first_entity, second_entity) = cx.update(|cx| {
+ let first_entity = cx.new(|_| ());
+ let second_entity = cx.new(|_| ());
+ cx.observe(&first_entity, {
+ let first_notification_count = first_notification_count.clone();
+ move |_, _| first_notification_count.set(first_notification_count.get() + 1)
+ })
+ .detach();
+ cx.observe(&second_entity, {
+ let second_notification_count = second_notification_count.clone();
+ move |_, _| second_notification_count.set(second_notification_count.get() + 1)
+ })
+ .detach();
+ (first_entity, second_entity)
+ });
+
+ assert_eq!(load.use_by(first_entity.entity_id()), None);
+ assert_eq!(load.use_by(first_entity.entity_id()), None);
+ assert_eq!(load.use_by(second_entity.entity_id()), None);
+
+ assert!(sender.send(42).is_ok());
+ cx.run_until_parked();
+
+ assert_eq!(first_notification_count.get(), 1);
+ assert_eq!(second_notification_count.get(), 1);
+ assert_eq!(load.use_by(first_entity.entity_id()), Some(42));
+ assert_eq!(load.use_by(second_entity.entity_id()), Some(42));
+ }
+
+ #[gpui::test]
+ fn removing_pending_asset_cancels_it_and_replacement_ignores_stale_completion(
+ cx: &mut TestAppContext,
+ ) {
+ let (stale_sender, stale_receiver) = oneshot::channel();
+ let (replacement_sender, replacement_receiver) = oneshot::channel();
+ let source = TestAssetSource::new(2, [stale_receiver, replacement_receiver]);
+
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+ assert_eq!(source.load_count(), 1);
+ cx.run_until_parked();
+
+ cx.update(|cx| cx.remove_asset::<TestAsset>(&source));
+ assert!(!cx.update(|cx| cx.has_asset::<TestAsset>(&source)));
+ cx.run_until_parked();
+ assert!(stale_sender.send(Ok(1)).is_err());
+
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+ assert_eq!(source.load_count(), 2);
+
+ assert!(replacement_sender.send(Err("replacement failed")).is_ok());
+ cx.run_until_parked();
+
+ assert_eq!(
+ cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)),
+ Some(Err("replacement failed"))
+ );
+ assert_eq!(source.load_count(), 2);
+ }
+
+ #[gpui::test]
+ fn eviction_after_worker_completion_does_not_publish_into_replacement(cx: &mut TestAppContext) {
+ let (sender, receiver) = oneshot::channel();
+ let (replacement_sender, replacement_receiver) = oneshot::channel();
+ let source = TestAssetSource::new(3, [receiver, replacement_receiver]);
+
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+ assert!(sender.send(Ok(1)).is_ok());
+ while source.completion_count.load(Ordering::SeqCst) == 0 {
+ assert!(cx.background_executor.tick());
+ }
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+
+ cx.update(|cx| {
+ cx.remove_asset::<TestAsset>(&source);
+ assert_eq!(cx.fetch_asset::<TestAsset>(&source), None);
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)), None);
+
+ assert!(replacement_sender.send(Ok(2)).is_ok());
+ cx.run_until_parked();
+ assert_eq!(
+ cx.update(|cx| cx.fetch_asset::<TestAsset>(&source)),
+ Some(Ok(2))
+ );
+ assert_eq!(source.load_count(), 2);
+ }
+
+ struct TestAsset;
+
+ #[derive(Clone)]
+ struct TestAssetSource {
+ id: usize,
+ load_count: Arc<AtomicUsize>,
+ completion_count: Arc<AtomicUsize>,
+ receivers: Arc<Mutex<VecDeque<oneshot::Receiver<Result<i32, &'static str>>>>>,
+ }
+
+ impl TestAssetSource {
+ fn new(
+ id: usize,
+ receivers: impl IntoIterator<Item = oneshot::Receiver<Result<i32, &'static str>>>,
+ ) -> Self {
+ Self {
+ id,
+ load_count: Arc::new(AtomicUsize::new(0)),
+ completion_count: Arc::new(AtomicUsize::new(0)),
+ receivers: Arc::new(Mutex::new(receivers.into_iter().collect())),
+ }
+ }
+
+ fn load_count(&self) -> usize {
+ self.load_count.load(Ordering::SeqCst)
+ }
+ }
+
+ impl Hash for TestAssetSource {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.id.hash(state);
+ }
+ }
+
+ impl Asset for TestAsset {
+ type Source = TestAssetSource;
+ type Output = Result<i32, &'static str>;
+
+ fn load(
+ source: Self::Source,
+ _cx: &mut App,
+ ) -> impl Future<Output = Self::Output> + Send + 'static {
+ source.load_count.fetch_add(1, Ordering::SeqCst);
+ let receiver = source
+ .receivers
+ .lock()
+ .expect("test receiver mutex should not be poisoned")
+ .pop_front()
+ .expect("each test load should have a receiver");
+ async move {
+ let result = match receiver.await {
+ Ok(result) => result,
+ Err(_) => Err("cancelled"),
+ };
+ source.completion_count.fetch_add(1, Ordering::SeqCst);
+ result
+ }
+ }
+ }
+}
diff --git a/crates/gpui/src/elements/image_cache.rs b/crates/gpui/src/elements/image_cache.rs
index ee1436134a3..84948145aa8 100644
--- a/crates/gpui/src/elements/image_cache.rs
+++ b/crates/gpui/src/elements/image_cache.rs
@@ -1,11 +1,10 @@
use crate::{
AnyElement, AnyEntity, App, AppContext, Asset, AssetLogger, Bounds, Element, ElementId, Entity,
GlobalElementId, ImageAssetLoader, ImageCacheError, InspectorElementId, IntoElement, LayoutId,
- ParentElement, Pixels, RenderImage, Resource, Style, StyleRefinement, Styled, Task, Window,
- hash,
+ ParentElement, Pixels, RenderImage, Resource, Style, StyleRefinement, Styled, Window, hash,
};
-use futures::{FutureExt, future::Shared};
+use crate::asset_cache::CachedLoad;
use refineable::Refineable;
use smallvec::SmallVec;
use std::{collections::HashMap, fmt, sync::Arc};
@@ -161,40 +160,35 @@ impl Element for ImageCacheElement {
}
}
-/// An image loading task associated with an image cache.
-pub type ImageLoadingTask = Shared<Task<Result<Arc<RenderImage>, ImageCacheError>>>;
-
-/// An image cache item
-pub enum ImageCacheItem {
- /// The associated image is currently loading
- Loading(ImageLoadingTask),
- /// This item has loaded an image.
- Loaded(Result<Arc<RenderImage>, ImageCacheError>),
-}
+/// Owns an image load and its cached result.
+///
+/// Dropping the entry cancels a pending load. Image caches must remove loaded
+/// images from windows before discarding the entry.
+pub struct ImageCacheItem(CachedLoad<Result<Arc<RenderImage>, ImageCacheError>>);
impl std::fmt::Debug for ImageCacheItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let status = match self {
- ImageCacheItem::Loading(_) => &"Loading...".to_string(),
- ImageCacheItem::Loaded(render_image) => &format!("{:?}", render_image),
- };
f.debug_struct("ImageCacheItem")
- .field("status", status)
+ .field("result", &self.get())
.finish()
}
}
impl ImageCacheItem {
- /// Attempt to get the image from the cache item.
- pub fn get(&mut self) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
- match self {
- ImageCacheItem::Loading(task) => {
- let res = task.now_or_never()?;
- *self = ImageCacheItem::Loaded(res.clone());
- Some(res)
- }
- ImageCacheItem::Loaded(res) => Some(res.clone()),
- }
+ /// Starts loading an image into a new cache entry.
+ pub fn new(source: &Resource, cx: &mut App) -> Self {
+ let future = AssetLogger::<ImageAssetLoader>::load(source.clone(), cx);
+ Self(CachedLoad::new(future, cx))
+ }
+
+ /// Returns the cached result without subscribing to completion notifications.
+ pub fn get(&self) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
+ self.0.get()
+ }
+
+ /// Returns the cached result or subscribes the current view to completion.
+ pub fn use_image(&self, window: &Window) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
+ self.0.use_by(window.current_view())
}
}
@@ -241,7 +235,7 @@ impl RetainAllImageCache {
pub fn new(cx: &mut App) -> Entity<Self> {
let e = cx.new(|_cx| RetainAllImageCache(HashMap::new()));
cx.observe_release(&e, |image_cache, cx| {
- for (_, mut item) in std::mem::replace(&mut image_cache.0, HashMap::new()) {
+ for (_, item) in std::mem::replace(&mut image_cache.0, HashMap::new()) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, None);
}
@@ -262,32 +256,15 @@ impl RetainAllImageCache {
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
let hash = hash(source);
- if let Some(item) = self.0.get_mut(&hash) {
- return item.get();
- }
-
- let fut = AssetLogger::<ImageAssetLoader>::load(source.clone(), cx);
- let task = cx.background_executor().spawn(fut).shared();
- self.0.insert(hash, ImageCacheItem::Loading(task.clone()));
-
- let entity = window.current_view();
- window
- .spawn(cx, {
- async move |cx| {
- _ = task.await;
- cx.on_next_frame(move |_, cx| {
- cx.notify(entity);
- });
- }
- })
- .detach();
-
- None
+ self.0
+ .entry(hash)
+ .or_insert_with(|| ImageCacheItem::new(source, cx))
+ .use_image(window)
}
/// Clear the image cache.
pub fn clear(&mut self, window: &mut Window, cx: &mut App) {
- for (_, mut item) in std::mem::replace(&mut self.0, HashMap::new()) {
+ for (_, item) in std::mem::replace(&mut self.0, HashMap::new()) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, Some(window));
}
@@ -297,7 +274,7 @@ impl RetainAllImageCache {
/// Remove the image from the cache by the given source.
pub fn remove(&mut self, source: &Resource, window: &mut Window, cx: &mut App) {
let hash = hash(source);
- if let Some(mut item) = self.0.remove(&hash)
+ if let Some(item) = self.0.remove(&hash)
&& let Some(Ok(image)) = item.get()
{
cx.drop_image(image, Some(window));
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 606623b5b08..e69cb685da5 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -32,7 +32,6 @@ use collections::{FxHashMap, FxHashSet};
#[cfg(target_os = "macos")]
use core_video::pixel_buffer::CVPixelBuffer;
use derive_more::{Deref, DerefMut};
-use futures::FutureExt;
use futures::channel::oneshot;
use gpui_util::post_inc;
use gpui_util::{ResultExt, measure};
@@ -3852,25 +3851,7 @@ impl Window {
/// Note that the multiple calls to this method will only result in one `Asset::load` call at a
/// time.
pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
- let (task, is_first) = cx.fetch_asset::<A>(source);
- task.clone().now_or_never().or_else(|| {
- if is_first {
- let entity_id = self.current_view();
- self.spawn(cx, {
- let task = task.clone();
- async move |cx| {
- task.await;
-
- cx.on_next_frame(move |_, cx| {
- cx.notify(entity_id);
- });
- }
- })
- .detach();
- }
-
- None
- })
+ cx.asset_entry::<A>(source).use_by(self.current_view())
}
/// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
@@ -3879,8 +3860,7 @@ impl Window {
/// Note that the multiple calls to this method will only result in one `Asset::load` call at a
/// time.
pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
- let (task, _) = cx.fetch_asset::<A>(source);
- task.now_or_never()
+ cx.fetch_asset::<A>(source)
}
/// Obtain the current element offset. This method should only be called during the
/// prepaint phase of element drawing.
diff --git a/crates/language_model_core/Cargo.toml b/crates/language_model_core/Cargo.toml
index 825818f4322..4ee946ad2fe 100644
--- a/crates/language_model_core/Cargo.toml
+++ b/crates/language_model_core/Cargo.toml
@@ -13,7 +13,6 @@ path = "src/language_model_core.rs"
[dependencies]
anyhow.workspace = true
-async-lock.workspace = true
cloud_llm_client.workspace = true
collections.workspace = true
futures.workspace = true
@@ -27,5 +26,12 @@ serde_json.workspace = true
strum.workspace = true
thiserror.workspace = true
+[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+# Workspace inheritance would re-enable defaults, including blocking synchronization.
+async-lock = { version = "3.4.2", default-features = false }
+
+[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies]
+async-lock.workspace = true
+
[dev-dependencies]
pretty_assertions.workspace = true