Merge pull request #2189 from zed-industries/labeled-tasks

Labeled Tasks
This commit is contained in:
Kay Simmons 2023-02-21 21:31:47 -08:00 committed by GitHub
commit 24fcad3fa2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 277 additions and 87 deletions

View file

@ -33,6 +33,19 @@ struct LspStatus {
status: LanguageServerBinaryStatus, status: LanguageServerBinaryStatus,
} }
struct PendingWork<'a> {
language_server_name: &'a str,
progress_token: &'a str,
progress: &'a LanguageServerProgress,
}
#[derive(Default)]
struct Content {
icon: Option<&'static str>,
message: String,
action: Option<Box<dyn Action>>,
}
pub fn init(cx: &mut MutableAppContext) { pub fn init(cx: &mut MutableAppContext) {
cx.add_action(ActivityIndicator::show_error_message); cx.add_action(ActivityIndicator::show_error_message);
cx.add_action(ActivityIndicator::dismiss_error_message); cx.add_action(ActivityIndicator::dismiss_error_message);
@ -69,6 +82,8 @@ impl ActivityIndicator {
if let Some(auto_updater) = auto_updater.as_ref() { if let Some(auto_updater) = auto_updater.as_ref() {
cx.observe(auto_updater, |_, _, cx| cx.notify()).detach(); cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
} }
cx.observe_active_labeled_tasks(|_, cx| cx.notify())
.detach();
Self { Self {
statuses: Default::default(), statuses: Default::default(),
@ -130,7 +145,7 @@ impl ActivityIndicator {
fn pending_language_server_work<'a>( fn pending_language_server_work<'a>(
&self, &self,
cx: &'a AppContext, cx: &'a AppContext,
) -> impl Iterator<Item = (&'a str, &'a str, &'a LanguageServerProgress)> { ) -> impl Iterator<Item = PendingWork<'a>> {
self.project self.project
.read(cx) .read(cx)
.language_server_statuses() .language_server_statuses()
@ -142,23 +157,29 @@ impl ActivityIndicator {
let mut pending_work = status let mut pending_work = status
.pending_work .pending_work
.iter() .iter()
.map(|(token, progress)| (status.name.as_str(), token.as_str(), progress)) .map(|(token, progress)| PendingWork {
language_server_name: status.name.as_str(),
progress_token: token.as_str(),
progress,
})
.collect::<SmallVec<[_; 4]>>(); .collect::<SmallVec<[_; 4]>>();
pending_work.sort_by_key(|(_, _, progress)| Reverse(progress.last_update_at)); pending_work.sort_by_key(|work| Reverse(work.progress.last_update_at));
Some(pending_work) Some(pending_work)
} }
}) })
.flatten() .flatten()
} }
fn content_to_render( fn content_to_render(&mut self, cx: &mut RenderContext<Self>) -> Content {
&mut self,
cx: &mut RenderContext<Self>,
) -> (Option<&'static str>, String, Option<Box<dyn Action>>) {
// Show any language server has pending activity. // Show any language server has pending activity.
let mut pending_work = self.pending_language_server_work(cx); let mut pending_work = self.pending_language_server_work(cx);
if let Some((lang_server_name, progress_token, progress)) = pending_work.next() { if let Some(PendingWork {
let mut message = lang_server_name.to_string(); language_server_name,
progress_token,
progress,
}) = pending_work.next()
{
let mut message = language_server_name.to_string();
message.push_str(": "); message.push_str(": ");
if let Some(progress_message) = progress.message.as_ref() { if let Some(progress_message) = progress.message.as_ref() {
@ -176,7 +197,11 @@ impl ActivityIndicator {
write!(&mut message, " + {} more", additional_work_count).unwrap(); write!(&mut message, " + {} more", additional_work_count).unwrap();
} }
return (None, message, None); return Content {
icon: None,
message,
action: None,
};
} }
// Show any language server installation info. // Show any language server installation info.
@ -199,19 +224,19 @@ impl ActivityIndicator {
} }
if !downloading.is_empty() { if !downloading.is_empty() {
return ( return Content {
Some(DOWNLOAD_ICON), icon: Some(DOWNLOAD_ICON),
format!( message: format!(
"Downloading {} language server{}...", "Downloading {} language server{}...",
downloading.join(", "), downloading.join(", "),
if downloading.len() > 1 { "s" } else { "" } if downloading.len() > 1 { "s" } else { "" }
), ),
None, action: None,
); };
} else if !checking_for_update.is_empty() { } else if !checking_for_update.is_empty() {
return ( return Content {
Some(DOWNLOAD_ICON), icon: Some(DOWNLOAD_ICON),
format!( message: format!(
"Checking for updates to {} language server{}...", "Checking for updates to {} language server{}...",
checking_for_update.join(", "), checking_for_update.join(", "),
if checking_for_update.len() > 1 { if checking_for_update.len() > 1 {
@ -220,54 +245,62 @@ impl ActivityIndicator {
"" ""
} }
), ),
None, action: None,
); };
} else if !failed.is_empty() { } else if !failed.is_empty() {
return ( return Content {
Some(WARNING_ICON), icon: Some(WARNING_ICON),
format!( message: format!(
"Failed to download {} language server{}. Click to show error.", "Failed to download {} language server{}. Click to show error.",
failed.join(", "), failed.join(", "),
if failed.len() > 1 { "s" } else { "" } if failed.len() > 1 { "s" } else { "" }
), ),
Some(Box::new(ShowErrorMessage)), action: Some(Box::new(ShowErrorMessage)),
); };
} }
// Show any application auto-update info. // Show any application auto-update info.
if let Some(updater) = &self.auto_updater { if let Some(updater) = &self.auto_updater {
match &updater.read(cx).status() { return match &updater.read(cx).status() {
AutoUpdateStatus::Checking => ( AutoUpdateStatus::Checking => Content {
Some(DOWNLOAD_ICON), icon: Some(DOWNLOAD_ICON),
"Checking for Zed updates…".to_string(), message: "Checking for Zed updates…".to_string(),
None, action: None,
), },
AutoUpdateStatus::Downloading => ( AutoUpdateStatus::Downloading => Content {
Some(DOWNLOAD_ICON), icon: Some(DOWNLOAD_ICON),
"Downloading Zed update…".to_string(), message: "Downloading Zed update…".to_string(),
None, action: None,
), },
AutoUpdateStatus::Installing => ( AutoUpdateStatus::Installing => Content {
Some(DOWNLOAD_ICON), icon: Some(DOWNLOAD_ICON),
"Installing Zed update…".to_string(), message: "Installing Zed update…".to_string(),
None, action: None,
), },
AutoUpdateStatus::Updated => ( AutoUpdateStatus::Updated => Content {
None, icon: None,
"Click to restart and update Zed".to_string(), message: "Click to restart and update Zed".to_string(),
Some(Box::new(workspace::Restart)), action: Some(Box::new(workspace::Restart)),
), },
AutoUpdateStatus::Errored => ( AutoUpdateStatus::Errored => Content {
Some(WARNING_ICON), icon: Some(WARNING_ICON),
"Auto update failed".to_string(), message: "Auto update failed".to_string(),
Some(Box::new(DismissErrorMessage)), action: Some(Box::new(DismissErrorMessage)),
), },
AutoUpdateStatus::Idle => Default::default(), AutoUpdateStatus::Idle => Default::default(),
};
} }
} else {
if let Some(most_recent_active_task) = cx.active_labeled_tasks().last() {
return Content {
icon: None,
message: most_recent_active_task.to_string(),
action: None,
};
}
Default::default() Default::default()
} }
}
} }
impl Entity for ActivityIndicator { impl Entity for ActivityIndicator {
@ -280,7 +313,11 @@ impl View for ActivityIndicator {
} }
fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox { fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
let (icon, message, action) = self.content_to_render(cx); let Content {
icon,
message,
action,
} = self.content_to_render(cx);
let mut element = MouseEventHandler::<Self>::new(0, cx, |state, cx| { let mut element = MouseEventHandler::<Self>::new(0, cx, |state, cx| {
let theme = &cx let theme = &cx

View file

@ -5071,7 +5071,7 @@ impl Editor {
GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx), GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
}); });
cx.spawn(|workspace, mut cx| async move { cx.spawn_labeled("Fetching Definition...", |workspace, mut cx| async move {
let definitions = definitions.await?; let definitions = definitions.await?;
workspace.update(&mut cx, |workspace, cx| { workspace.update(&mut cx, |workspace, cx| {
Editor::navigate_to_definitions(workspace, editor_handle, definitions, cx); Editor::navigate_to_definitions(workspace, editor_handle, definitions, cx);
@ -5151,7 +5151,9 @@ impl Editor {
let project = workspace.project().clone(); let project = workspace.project().clone();
let references = project.update(cx, |project, cx| project.references(&buffer, head, cx)); let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
Some(cx.spawn(|workspace, mut cx| async move { Some(cx.spawn_labeled(
"Finding All References...",
|workspace, mut cx| async move {
let locations = references.await?; let locations = references.await?;
if locations.is_empty() { if locations.is_empty() {
return Ok(()); return Ok(());
@ -5171,11 +5173,14 @@ impl Editor {
) )
}) })
.unwrap(); .unwrap();
Self::open_locations_in_multibuffer(workspace, locations, replica_id, title, cx); Self::open_locations_in_multibuffer(
workspace, locations, replica_id, title, cx,
);
}); });
Ok(()) Ok(())
})) },
))
} }
/// Opens a multibuffer with the given project locations in it /// Opens a multibuffer with the given project locations in it

View file

@ -31,7 +31,7 @@ use uuid::Uuid;
pub use action::*; pub use action::*;
use callback_collection::CallbackCollection; use callback_collection::CallbackCollection;
use collections::{hash_map::Entry, HashMap, HashSet, VecDeque}; use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
pub use menu::*; pub use menu::*;
use platform::Event; use platform::Event;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
@ -474,6 +474,7 @@ type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut MutableAppCon
type KeystrokeCallback = Box< type KeystrokeCallback = Box<
dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut MutableAppContext) -> bool, dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut MutableAppContext) -> bool,
>; >;
type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>; type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>; type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
@ -503,6 +504,7 @@ pub struct MutableAppContext {
window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>, window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>, window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>,
keystroke_observations: CallbackCollection<usize, KeystrokeCallback>, keystroke_observations: CallbackCollection<usize, KeystrokeCallback>,
active_labeled_task_observations: CallbackCollection<(), ActiveLabeledTasksCallback>,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
presenters_and_platform_windows: presenters_and_platform_windows:
@ -514,6 +516,8 @@ pub struct MutableAppContext {
pending_flushes: usize, pending_flushes: usize,
flushing_effects: bool, flushing_effects: bool,
halt_action_dispatch: bool, halt_action_dispatch: bool,
next_labeled_task_id: usize,
active_labeled_tasks: BTreeMap<usize, &'static str>,
} }
impl MutableAppContext { impl MutableAppContext {
@ -562,6 +566,7 @@ impl MutableAppContext {
window_bounds_observations: Default::default(), window_bounds_observations: Default::default(),
keystroke_observations: Default::default(), keystroke_observations: Default::default(),
action_dispatch_observations: Default::default(), action_dispatch_observations: Default::default(),
active_labeled_task_observations: Default::default(),
presenters_and_platform_windows: Default::default(), presenters_and_platform_windows: Default::default(),
foreground, foreground,
pending_effects: VecDeque::new(), pending_effects: VecDeque::new(),
@ -570,6 +575,8 @@ impl MutableAppContext {
pending_flushes: 0, pending_flushes: 0,
flushing_effects: false, flushing_effects: false,
halt_action_dispatch: false, halt_action_dispatch: false,
next_labeled_task_id: 0,
active_labeled_tasks: Default::default(),
} }
} }
@ -794,6 +801,12 @@ impl MutableAppContext {
window.screen().display_uuid() window.screen().display_uuid()
} }
pub fn active_labeled_tasks<'a>(
&'a self,
) -> impl DoubleEndedIterator<Item = &'static str> + 'a {
self.active_labeled_tasks.values().cloned()
}
pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> { pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
let window_id = params.window_id; let window_id = params.window_id;
let view_id = params.view_id; let view_id = params.view_id;
@ -1160,6 +1173,19 @@ impl MutableAppContext {
) )
} }
pub fn observe_active_labeled_tasks<F>(&mut self, callback: F) -> Subscription
where
F: 'static + FnMut(&mut MutableAppContext) -> bool,
{
let subscription_id = post_inc(&mut self.next_subscription_id);
self.active_labeled_task_observations
.add_callback((), subscription_id, Box::new(callback));
Subscription::ActiveLabeledTasksObservation(
self.active_labeled_task_observations
.subscribe((), subscription_id),
)
}
pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) { pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
self.pending_effects.push_back(Effect::Deferred { self.pending_effects.push_back(Effect::Deferred {
callback: Box::new(callback), callback: Box::new(callback),
@ -2042,6 +2068,17 @@ impl MutableAppContext {
handled_by, handled_by,
result, result,
} => self.handle_keystroke_effect(window_id, keystroke, handled_by, result), } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
Effect::ActiveLabeledTasksChanged => {
self.handle_active_labeled_tasks_changed_effect()
}
Effect::ActiveLabeledTasksObservation {
subscription_id,
callback,
} => self.active_labeled_task_observations.add_callback(
(),
subscription_id,
callback,
),
} }
self.pending_notifications.clear(); self.pending_notifications.clear();
self.remove_dropped_entities(); self.remove_dropped_entities();
@ -2449,26 +2486,68 @@ impl MutableAppContext {
} }
} }
fn handle_active_labeled_tasks_changed_effect(&mut self) {
self.active_labeled_task_observations
.clone()
.emit((), self, move |callback, this| {
callback(this);
true
});
}
pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) { pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
self.pending_effects self.pending_effects
.push_back(Effect::Focus { window_id, view_id }); .push_back(Effect::Focus { window_id, view_id });
} }
pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T> fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
where where
F: FnOnce(AsyncAppContext) -> Fut, F: FnOnce(AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = T>, Fut: 'static + Future<Output = T>,
T: 'static, T: 'static,
{ {
let label_id = task_name.map(|task_name| {
let id = post_inc(&mut self.next_labeled_task_id);
self.active_labeled_tasks.insert(id, task_name);
self.pending_effects
.push_back(Effect::ActiveLabeledTasksChanged);
id
});
let future = f(self.to_async()); let future = f(self.to_async());
let cx = self.to_async(); let cx = self.to_async();
self.foreground.spawn(async move { self.foreground.spawn(async move {
let result = future.await; let result = future.await;
cx.0.borrow_mut().flush_effects(); let mut cx = cx.0.borrow_mut();
if let Some(completed_label_id) = label_id {
cx.active_labeled_tasks.remove(&completed_label_id);
cx.pending_effects
.push_back(Effect::ActiveLabeledTasksChanged);
}
cx.flush_effects();
result result
}) })
} }
pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
where
F: FnOnce(AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = T>,
T: 'static,
{
self.spawn_internal(Some(task_name), f)
}
pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
where
F: FnOnce(AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = T>,
T: 'static,
{
self.spawn_internal(None, f)
}
pub fn to_async(&self) -> AsyncAppContext { pub fn to_async(&self) -> AsyncAppContext {
AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap()) AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
} }
@ -2907,6 +2986,11 @@ pub enum Effect {
window_id: usize, window_id: usize,
callback: WindowShouldCloseSubscriptionCallback, callback: WindowShouldCloseSubscriptionCallback,
}, },
ActiveLabeledTasksChanged,
ActiveLabeledTasksObservation {
subscription_id: usize,
callback: ActiveLabeledTasksCallback,
},
} }
impl Debug for Effect { impl Debug for Effect {
@ -3066,6 +3150,16 @@ impl Debug for Effect {
) )
.field("result", result) .field("result", result)
.finish(), .finish(),
Effect::ActiveLabeledTasksChanged => {
f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
}
Effect::ActiveLabeledTasksObservation {
subscription_id,
callback: _,
} => f
.debug_struct("Effect::ActiveLabeledTasksObservation")
.field("subscription_id", subscription_id)
.finish(),
} }
} }
} }
@ -3480,7 +3574,7 @@ impl<'a, T: Entity> ModelContext<'a, T> {
WeakModelHandle::new(self.model_id) WeakModelHandle::new(self.model_id)
} }
pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S> pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
where where
F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut, F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = S>, Fut: 'static + Future<Output = S>,
@ -3490,7 +3584,7 @@ impl<'a, T: Entity> ModelContext<'a, T> {
self.app.spawn(|cx| f(handle, cx)) self.app.spawn(|cx| f(handle, cx))
} }
pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S> pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
where where
F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut, F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = S>, Fut: 'static + Future<Output = S>,
@ -3947,6 +4041,23 @@ impl<'a, T: View> ViewContext<'a, T> {
}) })
} }
pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut T, &mut ViewContext<T>),
{
let observer = self.weak_handle();
self.app.observe_active_labeled_tasks(move |cx| {
if let Some(observer) = observer.upgrade(cx) {
observer.update(cx, |observer, cx| {
callback(observer, cx);
});
true
} else {
false
}
})
}
pub fn emit(&mut self, payload: T::Event) { pub fn emit(&mut self, payload: T::Event) {
self.app.pending_effects.push_back(Effect::Event { self.app.pending_effects.push_back(Effect::Event {
entity_id: self.view_id, entity_id: self.view_id,
@ -3993,7 +4104,17 @@ impl<'a, T: View> ViewContext<'a, T> {
self.app.halt_action_dispatch = false; self.app.halt_action_dispatch = false;
} }
pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S> pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
where
F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = S>,
S: 'static,
{
let handle = self.handle();
self.app.spawn_labeled(task_label, |cx| f(handle, cx))
}
pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
where where
F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut, F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = S>, Fut: 'static + Future<Output = S>,
@ -4003,7 +4124,7 @@ impl<'a, T: View> ViewContext<'a, T> {
self.app.spawn(|cx| f(handle, cx)) self.app.spawn(|cx| f(handle, cx))
} }
pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S> pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
where where
F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut, F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
Fut: 'static + Future<Output = S>, Fut: 'static + Future<Output = S>,
@ -5121,6 +5242,9 @@ pub enum Subscription {
KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>), KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>), ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>), ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
ActiveLabeledTasksObservation(
callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
),
} }
impl Subscription { impl Subscription {
@ -5137,6 +5261,7 @@ impl Subscription {
Subscription::KeystrokeObservation(subscription) => subscription.id(), Subscription::KeystrokeObservation(subscription) => subscription.id(),
Subscription::ReleaseObservation(subscription) => subscription.id(), Subscription::ReleaseObservation(subscription) => subscription.id(),
Subscription::ActionObservation(subscription) => subscription.id(), Subscription::ActionObservation(subscription) => subscription.id(),
Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
} }
} }
@ -5153,6 +5278,7 @@ impl Subscription {
Subscription::WindowBoundsObservation(subscription) => subscription.detach(), Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
Subscription::ReleaseObservation(subscription) => subscription.detach(), Subscription::ReleaseObservation(subscription) => subscription.detach(),
Subscription::ActionObservation(subscription) => subscription.detach(), Subscription::ActionObservation(subscription) => subscription.detach(),
Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
} }
} }
} }
@ -5161,6 +5287,7 @@ impl Subscription {
mod tests { mod tests {
use super::*; use super::*;
use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent}; use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
use postage::{sink::Sink, stream::Stream};
use serde::Deserialize; use serde::Deserialize;
use smol::future::poll_once; use smol::future::poll_once;
use std::{ use std::{
@ -6776,6 +6903,26 @@ mod tests {
assert_eq!(presenter.borrow().rendered_views.len(), 1); assert_eq!(presenter.borrow().rendered_views.len(), 1);
} }
#[crate::test(self)]
async fn test_labeled_tasks(cx: &mut TestAppContext) {
assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
let task = cx
.update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
assert_eq!(
Some("Test Label"),
cx.update(|cx| cx.active_labeled_tasks().next())
);
sender
.send(())
.await
.expect("Could not send message to complete task");
task.await;
assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
}
#[crate::test(self)] #[crate::test(self)]
async fn test_window_activation(cx: &mut TestAppContext) { async fn test_window_activation(cx: &mut TestAppContext) {
struct View(&'static str); struct View(&'static str);

View file

@ -227,7 +227,7 @@ mod tests {
#[test] #[test]
fn test_push_keystroke() -> Result<()> { fn test_push_keystroke() -> Result<()> {
actions!(test, [B, AB, C, D, DA]); actions!(test, [B, AB, C, D, DA, E, EF]);
let mut context1 = KeymapContext::default(); let mut context1 = KeymapContext::default();
context1.set.insert("1".into()); context1.set.insert("1".into());
@ -286,6 +286,7 @@ mod tests {
matcher.push_keystroke(Keystroke::parse("d")?, dispatch_path.clone()), matcher.push_keystroke(Keystroke::parse("d")?, dispatch_path.clone()),
MatchResult::Matches(vec![(2, Box::new(D)), (1, Box::new(D))]), MatchResult::Matches(vec![(2, Box::new(D)), (1, Box::new(D))]),
); );
// If none of the d action handlers consume the binding, a pending // If none of the d action handlers consume the binding, a pending
// binding may then be used // binding may then be used
assert_eq!( assert_eq!(