1use std::sync::Arc;
2
3use crate::{active_item_selection_properties, schedule_task};
4use fuzzy::{StringMatch, StringMatchCandidate};
5use gpui::{
6 impl_actions, rems, AppContext, DismissEvent, EventEmitter, FocusableView, Global,
7 InteractiveElement, Model, ParentElement, Render, SharedString, Styled, Subscription, View,
8 ViewContext, VisualContext, WeakView,
9};
10use picker::{highlighted_match_with_paths::HighlightedText, Picker, PickerDelegate};
11use project::{Inventory, TaskSourceKind};
12use task::{oneshot_source::OneshotSource, Task, TaskContext};
13use ui::{
14 div, v_flex, ButtonCommon, ButtonSize, Clickable, Color, FluentBuilder as _, Icon, IconButton,
15 IconButtonShape, IconName, IconSize, ListItem, ListItemSpacing, RenderOnce, Selectable,
16 Tooltip, WindowContext,
17};
18use util::ResultExt;
19use workspace::{ModalView, Workspace};
20
21use serde::Deserialize;
22
23/// Spawn a task with name or open tasks modal
24#[derive(PartialEq, Clone, Deserialize, Default)]
25pub struct Spawn {
26 #[serde(default)]
27 /// Name of the task to spawn.
28 /// If it is not set, a modal with a list of available tasks is opened instead.
29 /// Defaults to None.
30 pub task_name: Option<String>,
31}
32
33impl Spawn {
34 pub(crate) fn modal() -> Self {
35 Self { task_name: None }
36 }
37}
38/// Rerun last task
39#[derive(PartialEq, Clone, Deserialize, Default)]
40pub struct Rerun {
41 #[serde(default)]
42 /// Controls whether the task context is reevaluated prior to execution of a task.
43 /// If it is not, environment variables such as ZED_COLUMN, ZED_FILE are gonna be the same as in the last execution of a task
44 /// If it is, these variables will be updated to reflect current state of editor at the time task::Rerun is executed.
45 /// default: false
46 pub reevaluate_context: bool,
47}
48
49impl_actions!(task, [Rerun, Spawn]);
50
51/// A modal used to spawn new tasks.
52pub(crate) struct TasksModalDelegate {
53 inventory: Model<Inventory>,
54 candidates: Option<Vec<(TaskSourceKind, Arc<dyn Task>)>>,
55 matches: Vec<StringMatch>,
56 selected_index: usize,
57 workspace: WeakView<Workspace>,
58 prompt: String,
59 task_context: TaskContext,
60 placeholder_text: Arc<str>,
61}
62
63impl TasksModalDelegate {
64 fn new(
65 inventory: Model<Inventory>,
66 task_context: TaskContext,
67 workspace: WeakView<Workspace>,
68 ) -> Self {
69 Self {
70 inventory,
71 workspace,
72 candidates: None,
73 matches: Vec::new(),
74 selected_index: 0,
75 prompt: String::default(),
76 task_context,
77 placeholder_text: Arc::from("Run a task..."),
78 }
79 }
80
81 fn spawn_oneshot(&mut self, cx: &mut AppContext) -> Option<Arc<dyn Task>> {
82 if self.prompt.trim().is_empty() {
83 return None;
84 }
85
86 self.inventory
87 .update(cx, |inventory, _| inventory.source::<OneshotSource>())?
88 .update(cx, |oneshot_source, _| {
89 Some(
90 oneshot_source
91 .as_any()
92 .downcast_mut::<OneshotSource>()?
93 .spawn(self.prompt.clone()),
94 )
95 })
96 }
97
98 fn delete_oneshot(&mut self, ix: usize, cx: &mut AppContext) {
99 let Some(candidates) = self.candidates.as_mut() else {
100 return;
101 };
102 let Some(task) = candidates.get(ix).map(|(_, task)| task.clone()) else {
103 return;
104 };
105 // We remove this candidate manually instead of .taking() the candidates, as we already know the index;
106 // it doesn't make sense to requery the inventory for new candidates, as that's potentially costly and more often than not it should just return back
107 // the original list without a removed entry.
108 candidates.remove(ix);
109 self.inventory.update(cx, |inventory, cx| {
110 let oneshot_source = inventory.source::<OneshotSource>()?;
111 let task_id = task.id();
112
113 oneshot_source.update(cx, |this, _| {
114 let oneshot_source = this.as_any().downcast_mut::<OneshotSource>()?;
115 oneshot_source.remove(task_id);
116 Some(())
117 });
118 Some(())
119 });
120 }
121}
122
123pub(crate) struct TasksModal {
124 picker: View<Picker<TasksModalDelegate>>,
125 _subscription: Subscription,
126}
127
128impl TasksModal {
129 pub(crate) fn new(
130 inventory: Model<Inventory>,
131 task_context: TaskContext,
132 workspace: WeakView<Workspace>,
133 cx: &mut ViewContext<Self>,
134 ) -> Self {
135 let picker = cx.new_view(|cx| {
136 Picker::uniform_list(
137 TasksModalDelegate::new(inventory, task_context, workspace),
138 cx,
139 )
140 });
141 let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
142 cx.emit(DismissEvent);
143 });
144 Self {
145 picker,
146 _subscription,
147 }
148 }
149}
150
151impl Render for TasksModal {
152 fn render(&mut self, _: &mut ViewContext<Self>) -> impl gpui::prelude::IntoElement {
153 v_flex()
154 .key_context("TasksModal")
155 .w(rems(34.))
156 .child(self.picker.clone())
157 }
158}
159
160impl EventEmitter<DismissEvent> for TasksModal {}
161
162impl FocusableView for TasksModal {
163 fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
164 self.picker.read(cx).focus_handle(cx)
165 }
166}
167
168impl ModalView for TasksModal {}
169
170impl PickerDelegate for TasksModalDelegate {
171 type ListItem = ListItem;
172
173 fn match_count(&self) -> usize {
174 self.matches.len()
175 }
176
177 fn selected_index(&self) -> usize {
178 self.selected_index
179 }
180
181 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<picker::Picker<Self>>) {
182 self.selected_index = ix;
183 }
184
185 fn placeholder_text(&self, _: &mut WindowContext) -> Arc<str> {
186 self.placeholder_text.clone()
187 }
188
189 fn update_matches(
190 &mut self,
191 query: String,
192 cx: &mut ViewContext<picker::Picker<Self>>,
193 ) -> gpui::Task<()> {
194 cx.spawn(move |picker, mut cx| async move {
195 let Some(candidates) = picker
196 .update(&mut cx, |picker, cx| {
197 let candidates = picker.delegate.candidates.get_or_insert_with(|| {
198 let (worktree, language) =
199 active_item_selection_properties(&picker.delegate.workspace, cx);
200 picker.delegate.inventory.update(cx, |inventory, cx| {
201 inventory.list_tasks(language, worktree, true, cx)
202 })
203 });
204
205 candidates
206 .iter()
207 .enumerate()
208 .map(|(index, (_, candidate))| StringMatchCandidate {
209 id: index,
210 char_bag: candidate.name().chars().collect(),
211 string: candidate.name().into(),
212 })
213 .collect::<Vec<_>>()
214 })
215 .ok()
216 else {
217 return;
218 };
219 let matches = fuzzy::match_strings(
220 &candidates,
221 &query,
222 true,
223 1000,
224 &Default::default(),
225 cx.background_executor().clone(),
226 )
227 .await;
228 picker
229 .update(&mut cx, |picker, _| {
230 let delegate = &mut picker.delegate;
231 delegate.matches = matches;
232 delegate.prompt = query;
233
234 if delegate.matches.is_empty() {
235 delegate.selected_index = 0;
236 } else {
237 delegate.selected_index =
238 delegate.selected_index.min(delegate.matches.len() - 1);
239 }
240 })
241 .log_err();
242 })
243 }
244
245 fn confirm(&mut self, omit_history_entry: bool, cx: &mut ViewContext<picker::Picker<Self>>) {
246 let current_match_index = self.selected_index();
247 let task = self
248 .matches
249 .get(current_match_index)
250 .and_then(|current_match| {
251 let ix = current_match.candidate_id;
252 self.candidates
253 .as_ref()
254 .map(|candidates| candidates[ix].1.clone())
255 });
256 let Some(task) = task else {
257 return;
258 };
259
260 self.workspace
261 .update(cx, |workspace, cx| {
262 schedule_task(
263 workspace,
264 &task,
265 self.task_context.clone(),
266 omit_history_entry,
267 cx,
268 );
269 })
270 .ok();
271 cx.emit(DismissEvent);
272 }
273
274 fn dismissed(&mut self, cx: &mut ViewContext<picker::Picker<Self>>) {
275 cx.emit(DismissEvent);
276 }
277
278 fn render_match(
279 &self,
280 ix: usize,
281 selected: bool,
282 cx: &mut ViewContext<picker::Picker<Self>>,
283 ) -> Option<Self::ListItem> {
284 let candidates = self.candidates.as_ref()?;
285 let hit = &self.matches[ix];
286 let (source_kind, _) = &candidates[hit.candidate_id];
287 let language_name = if let TaskSourceKind::Language { name } = source_kind {
288 Some(name)
289 } else {
290 None
291 };
292
293 let highlighted_location = HighlightedText {
294 text: hit.string.clone(),
295 highlight_positions: hit.positions.clone(),
296 char_count: hit.string.chars().count(),
297 };
298 let language_icon = language_name
299 .and_then(|language| {
300 let language = language.to_lowercase();
301 file_icons::FileIcons::get(cx).get_type_icon(&language)
302 })
303 .map(|icon_path| Icon::from_path(icon_path));
304 Some(
305 ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
306 .inset(true)
307 .spacing(ListItemSpacing::Sparse)
308 .map(|this| {
309 let this = if matches!(source_kind, TaskSourceKind::UserInput) {
310 let task_index = hit.candidate_id;
311 let delete_button = div().child(
312 IconButton::new("delete", IconName::Close)
313 .shape(IconButtonShape::Square)
314 .icon_color(Color::Muted)
315 .size(ButtonSize::None)
316 .icon_size(IconSize::XSmall)
317 .on_click(cx.listener(move |this, _event, cx| {
318 cx.stop_propagation();
319 cx.prevent_default();
320
321 this.delegate.delete_oneshot(task_index, cx);
322 this.refresh(cx);
323 }))
324 .tooltip(|cx| Tooltip::text("Delete an one-shot task", cx)),
325 );
326 this.end_hover_slot(delete_button)
327 } else {
328 this
329 };
330 if let Some(icon) = language_icon {
331 this.end_slot(icon)
332 } else {
333 this
334 }
335 })
336 .selected(selected)
337 .child(highlighted_location.render(cx)),
338 )
339 }
340
341 fn selected_as_query(&self) -> Option<String> {
342 use itertools::intersperse;
343 let task_index = self.matches.get(self.selected_index())?.candidate_id;
344 let tasks = self.candidates.as_ref()?;
345 let (_, task) = tasks.get(task_index)?;
346 let mut spawn_prompt = task.prepare_exec(self.task_context.clone())?;
347 if !spawn_prompt.args.is_empty() {
348 spawn_prompt.command.push(' ');
349 spawn_prompt
350 .command
351 .extend(intersperse(spawn_prompt.args, " ".to_string()));
352 }
353 Some(spawn_prompt.command)
354 }
355
356 fn confirm_input(&mut self, omit_history_entry: bool, cx: &mut ViewContext<Picker<Self>>) {
357 let Some(task) = self.spawn_oneshot(cx) else {
358 return;
359 };
360 self.workspace
361 .update(cx, |workspace, cx| {
362 schedule_task(
363 workspace,
364 &task,
365 self.task_context.clone(),
366 omit_history_entry,
367 cx,
368 );
369 })
370 .ok();
371 cx.emit(DismissEvent);
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use gpui::{TestAppContext, VisualTestContext};
378 use project::{FakeFs, Project};
379 use serde_json::json;
380
381 use super::*;
382
383 #[gpui::test]
384 async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
385 crate::tests::init_test(cx);
386 let fs = FakeFs::new(cx.executor());
387 fs.insert_tree(
388 "/dir",
389 json!({
390 ".zed": {
391 "tasks.json": r#"[
392 {
393 "label": "example task",
394 "command": "echo",
395 "args": ["4"]
396 },
397 {
398 "label": "another one",
399 "command": "echo",
400 "args": ["55"]
401 },
402 ]"#,
403 },
404 "a.ts": "a"
405 }),
406 )
407 .await;
408
409 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
410 project.update(cx, |project, cx| {
411 project.task_inventory().update(cx, |inventory, cx| {
412 inventory.add_source(TaskSourceKind::UserInput, |cx| OneshotSource::new(cx), cx)
413 })
414 });
415
416 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
417
418 let tasks_picker = open_spawn_tasks(&workspace, cx);
419 assert_eq!(
420 query(&tasks_picker, cx),
421 "",
422 "Initial query should be empty"
423 );
424 assert_eq!(
425 task_names(&tasks_picker, cx),
426 vec!["another one", "example task"],
427 "Initial tasks should be listed in alphabetical order"
428 );
429
430 let query_str = "tas";
431 cx.simulate_input(query_str);
432 assert_eq!(query(&tasks_picker, cx), query_str);
433 assert_eq!(
434 task_names(&tasks_picker, cx),
435 vec!["example task"],
436 "Only one task should match the query {query_str}"
437 );
438
439 cx.dispatch_action(picker::UseSelectedQuery);
440 assert_eq!(
441 query(&tasks_picker, cx),
442 "echo 4",
443 "Query should be set to the selected task's command"
444 );
445 assert_eq!(
446 task_names(&tasks_picker, cx),
447 Vec::<String>::new(),
448 "No task should be listed"
449 );
450 cx.dispatch_action(picker::ConfirmInput { secondary: false });
451
452 let tasks_picker = open_spawn_tasks(&workspace, cx);
453 assert_eq!(
454 query(&tasks_picker, cx),
455 "",
456 "Query should be reset after confirming"
457 );
458 assert_eq!(
459 task_names(&tasks_picker, cx),
460 vec!["echo 4", "another one", "example task"],
461 "New oneshot task should be listed first"
462 );
463
464 let query_str = "echo 4";
465 cx.simulate_input(query_str);
466 assert_eq!(query(&tasks_picker, cx), query_str);
467 assert_eq!(
468 task_names(&tasks_picker, cx),
469 vec!["echo 4"],
470 "New oneshot should match custom command query"
471 );
472
473 cx.dispatch_action(picker::ConfirmInput { secondary: false });
474 let tasks_picker = open_spawn_tasks(&workspace, cx);
475 assert_eq!(
476 query(&tasks_picker, cx),
477 "",
478 "Query should be reset after confirming"
479 );
480 assert_eq!(
481 task_names(&tasks_picker, cx),
482 vec![query_str, "another one", "example task"],
483 "Last recently used one show task should be listed first"
484 );
485
486 cx.dispatch_action(picker::UseSelectedQuery);
487 assert_eq!(
488 query(&tasks_picker, cx),
489 query_str,
490 "Query should be set to the custom task's name"
491 );
492 assert_eq!(
493 task_names(&tasks_picker, cx),
494 vec![query_str],
495 "Only custom task should be listed"
496 );
497
498 let query_str = "0";
499 cx.simulate_input(query_str);
500 assert_eq!(query(&tasks_picker, cx), "echo 40");
501 assert_eq!(
502 task_names(&tasks_picker, cx),
503 Vec::<String>::new(),
504 "New oneshot should not match any command query"
505 );
506
507 cx.dispatch_action(picker::ConfirmInput { secondary: true });
508 let tasks_picker = open_spawn_tasks(&workspace, cx);
509 assert_eq!(
510 query(&tasks_picker, cx),
511 "",
512 "Query should be reset after confirming"
513 );
514 assert_eq!(
515 task_names(&tasks_picker, cx),
516 vec!["echo 4", "another one", "example task", "echo 40"],
517 "Last recently used one show task should be listed last, as it is a fire-and-forget task"
518 );
519 }
520
521 fn open_spawn_tasks(
522 workspace: &View<Workspace>,
523 cx: &mut VisualTestContext,
524 ) -> View<Picker<TasksModalDelegate>> {
525 cx.dispatch_action(crate::modal::Spawn::default());
526 workspace.update(cx, |workspace, cx| {
527 workspace
528 .active_modal::<TasksModal>(cx)
529 .unwrap()
530 .read(cx)
531 .picker
532 .clone()
533 })
534 }
535
536 fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
537 spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
538 }
539
540 fn task_names(
541 spawn_tasks: &View<Picker<TasksModalDelegate>>,
542 cx: &mut VisualTestContext,
543 ) -> Vec<String> {
544 spawn_tasks.update(cx, |spawn_tasks, _| {
545 spawn_tasks
546 .delegate
547 .matches
548 .iter()
549 .map(|hit| hit.string.clone())
550 .collect::<Vec<_>>()
551 })
552 }
553}