1use std::sync::Arc;
2
3use crate::{active_item_selection_properties, schedule_resolved_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::{ResolvedTask, TaskContext, TaskTemplate};
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 /// Controls whether the task context is reevaluated prior to execution of a task.
42 /// 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
43 /// If it is, these variables will be updated to reflect current state of editor at the time task::Rerun is executed.
44 /// default: false
45 #[serde(default)]
46 pub reevaluate_context: bool,
47 /// Overrides `allow_concurrent_runs` property of the task being reran.
48 /// Default: null
49 #[serde(default)]
50 pub allow_concurrent_runs: Option<bool>,
51 /// Overrides `use_new_terminal` property of the task being reran.
52 /// Default: null
53 #[serde(default)]
54 pub use_new_terminal: Option<bool>,
55}
56
57impl_actions!(task, [Rerun, Spawn]);
58
59/// A modal used to spawn new tasks.
60pub(crate) struct TasksModalDelegate {
61 inventory: Model<Inventory>,
62 candidates: Option<Vec<(TaskSourceKind, ResolvedTask)>>,
63 last_used_candidate_index: Option<usize>,
64 matches: Vec<StringMatch>,
65 selected_index: usize,
66 workspace: WeakView<Workspace>,
67 prompt: String,
68 task_context: TaskContext,
69 placeholder_text: Arc<str>,
70}
71
72impl TasksModalDelegate {
73 fn new(
74 inventory: Model<Inventory>,
75 task_context: TaskContext,
76 workspace: WeakView<Workspace>,
77 ) -> Self {
78 Self {
79 inventory,
80 workspace,
81 candidates: None,
82 matches: Vec::new(),
83 last_used_candidate_index: None,
84 selected_index: 0,
85 prompt: String::default(),
86 task_context,
87 placeholder_text: Arc::from("Run a task..."),
88 }
89 }
90
91 fn spawn_oneshot(&mut self) -> Option<(TaskSourceKind, ResolvedTask)> {
92 if self.prompt.trim().is_empty() {
93 return None;
94 }
95
96 let source_kind = TaskSourceKind::UserInput;
97 let id_base = source_kind.to_id_base();
98 let new_oneshot = TaskTemplate {
99 label: self.prompt.clone(),
100 command: self.prompt.clone(),
101 ..TaskTemplate::default()
102 };
103 Some((
104 source_kind,
105 new_oneshot.resolve_task(&id_base, &self.task_context)?,
106 ))
107 }
108
109 fn delete_previously_used(&mut self, ix: usize, cx: &mut AppContext) {
110 let Some(candidates) = self.candidates.as_mut() else {
111 return;
112 };
113 let Some(task) = candidates.get(ix).map(|(_, task)| task.clone()) else {
114 return;
115 };
116 // We remove this candidate manually instead of .taking() the candidates, as we already know the index;
117 // 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
118 // the original list without a removed entry.
119 candidates.remove(ix);
120 self.inventory.update(cx, |inventory, _| {
121 inventory.delete_previously_used(&task.id);
122 });
123 }
124}
125
126pub(crate) struct TasksModal {
127 picker: View<Picker<TasksModalDelegate>>,
128 _subscription: Subscription,
129}
130
131impl TasksModal {
132 pub(crate) fn new(
133 inventory: Model<Inventory>,
134 task_context: TaskContext,
135 workspace: WeakView<Workspace>,
136 cx: &mut ViewContext<Self>,
137 ) -> Self {
138 let picker = cx.new_view(|cx| {
139 Picker::uniform_list(
140 TasksModalDelegate::new(inventory, task_context, workspace),
141 cx,
142 )
143 });
144 let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
145 cx.emit(DismissEvent);
146 });
147 Self {
148 picker,
149 _subscription,
150 }
151 }
152}
153
154impl Render for TasksModal {
155 fn render(&mut self, _: &mut ViewContext<Self>) -> impl gpui::prelude::IntoElement {
156 v_flex()
157 .key_context("TasksModal")
158 .w(rems(34.))
159 .child(self.picker.clone())
160 }
161}
162
163impl EventEmitter<DismissEvent> for TasksModal {}
164
165impl FocusableView for TasksModal {
166 fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
167 self.picker.read(cx).focus_handle(cx)
168 }
169}
170
171impl ModalView for TasksModal {}
172
173impl PickerDelegate for TasksModalDelegate {
174 type ListItem = ListItem;
175
176 fn match_count(&self) -> usize {
177 self.matches.len()
178 }
179
180 fn selected_index(&self) -> usize {
181 self.selected_index
182 }
183
184 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<picker::Picker<Self>>) {
185 self.selected_index = ix;
186 }
187
188 fn placeholder_text(&self, _: &mut WindowContext) -> Arc<str> {
189 self.placeholder_text.clone()
190 }
191
192 fn update_matches(
193 &mut self,
194 query: String,
195 cx: &mut ViewContext<picker::Picker<Self>>,
196 ) -> gpui::Task<()> {
197 cx.spawn(move |picker, mut cx| async move {
198 let Some(candidates) = picker
199 .update(&mut cx, |picker, cx| {
200 let candidates = match &mut picker.delegate.candidates {
201 Some(candidates) => candidates,
202 None => {
203 let Ok((worktree, language)) =
204 picker.delegate.workspace.update(cx, |workspace, cx| {
205 active_item_selection_properties(workspace, cx)
206 })
207 else {
208 return Vec::new();
209 };
210 let (used, current) =
211 picker.delegate.inventory.update(cx, |inventory, cx| {
212 inventory.used_and_current_resolved_tasks(
213 language,
214 worktree,
215 &picker.delegate.task_context,
216 cx,
217 )
218 });
219 picker.delegate.last_used_candidate_index = if used.is_empty() {
220 None
221 } else {
222 Some(used.len() - 1)
223 };
224
225 let mut new_candidates = used;
226 new_candidates.extend(current);
227 picker.delegate.candidates.insert(new_candidates)
228 }
229 };
230 candidates
231 .iter()
232 .enumerate()
233 .map(|(index, (_, candidate))| StringMatchCandidate {
234 id: index,
235 char_bag: candidate.resolved_label.chars().collect(),
236 string: candidate.display_label().to_owned(),
237 })
238 .collect::<Vec<_>>()
239 })
240 .ok()
241 else {
242 return;
243 };
244 let matches = fuzzy::match_strings(
245 &candidates,
246 &query,
247 true,
248 1000,
249 &Default::default(),
250 cx.background_executor().clone(),
251 )
252 .await;
253 picker
254 .update(&mut cx, |picker, _| {
255 let delegate = &mut picker.delegate;
256 delegate.matches = matches;
257 delegate.prompt = query;
258
259 if delegate.matches.is_empty() {
260 delegate.selected_index = 0;
261 } else {
262 delegate.selected_index =
263 delegate.selected_index.min(delegate.matches.len() - 1);
264 }
265 })
266 .log_err();
267 })
268 }
269
270 fn confirm(&mut self, omit_history_entry: bool, cx: &mut ViewContext<picker::Picker<Self>>) {
271 let current_match_index = self.selected_index();
272 let task = self
273 .matches
274 .get(current_match_index)
275 .and_then(|current_match| {
276 let ix = current_match.candidate_id;
277 self.candidates
278 .as_ref()
279 .map(|candidates| candidates[ix].clone())
280 });
281 let Some((task_source_kind, task)) = task else {
282 return;
283 };
284
285 self.workspace
286 .update(cx, |workspace, cx| {
287 schedule_resolved_task(workspace, task_source_kind, task, omit_history_entry, cx);
288 })
289 .ok();
290 cx.emit(DismissEvent);
291 }
292
293 fn dismissed(&mut self, cx: &mut ViewContext<picker::Picker<Self>>) {
294 cx.emit(DismissEvent);
295 }
296
297 fn render_match(
298 &self,
299 ix: usize,
300 selected: bool,
301 cx: &mut ViewContext<picker::Picker<Self>>,
302 ) -> Option<Self::ListItem> {
303 let candidates = self.candidates.as_ref()?;
304 let hit = &self.matches[ix];
305 let (source_kind, resolved_task) = &candidates.get(hit.candidate_id)?;
306 let template = resolved_task.original_task();
307 let display_label = resolved_task.display_label();
308
309 let mut tooltip_label_text = if display_label != &template.label {
310 resolved_task.resolved_label.clone()
311 } else {
312 String::new()
313 };
314 if let Some(resolved) = resolved_task.resolved.as_ref() {
315 if display_label != resolved.command_label {
316 if !tooltip_label_text.trim().is_empty() {
317 tooltip_label_text.push('\n');
318 }
319 tooltip_label_text.push_str(&resolved.command_label);
320 }
321 }
322 let tooltip_label = if tooltip_label_text.trim().is_empty() {
323 None
324 } else {
325 Some(Tooltip::text(tooltip_label_text, cx))
326 };
327
328 let highlighted_location = HighlightedText {
329 text: hit.string.clone(),
330 highlight_positions: hit.positions.clone(),
331 char_count: hit.string.chars().count(),
332 };
333 let icon = match source_kind {
334 TaskSourceKind::UserInput => Some(Icon::new(IconName::Terminal)),
335 TaskSourceKind::AbsPath { .. } => Some(Icon::new(IconName::Settings)),
336 TaskSourceKind::Worktree { .. } => Some(Icon::new(IconName::FileTree)),
337 TaskSourceKind::Language { name } => file_icons::FileIcons::get(cx)
338 .get_type_icon(&name.to_lowercase())
339 .map(|icon_path| Icon::from_path(icon_path)),
340 };
341
342 Some(
343 ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
344 .inset(true)
345 .spacing(ListItemSpacing::Sparse)
346 .when_some(tooltip_label, |list_item, item_label| {
347 list_item.tooltip(move |_| item_label.clone())
348 })
349 .map(|item| {
350 let item = if matches!(source_kind, TaskSourceKind::UserInput)
351 || Some(ix) <= self.last_used_candidate_index
352 {
353 let task_index = hit.candidate_id;
354 let delete_button = div().child(
355 IconButton::new("delete", IconName::Close)
356 .shape(IconButtonShape::Square)
357 .icon_color(Color::Muted)
358 .size(ButtonSize::None)
359 .icon_size(IconSize::XSmall)
360 .on_click(cx.listener(move |picker, _event, cx| {
361 cx.stop_propagation();
362 cx.prevent_default();
363
364 picker.delegate.delete_previously_used(task_index, cx);
365 picker.delegate.last_used_candidate_index = picker
366 .delegate
367 .last_used_candidate_index
368 .unwrap_or(0)
369 .checked_sub(1);
370 picker.refresh(cx);
371 }))
372 .tooltip(|cx| {
373 Tooltip::text("Delete previously scheduled task", cx)
374 }),
375 );
376 item.end_hover_slot(delete_button)
377 } else {
378 item
379 };
380 if let Some(icon) = icon {
381 item.end_slot(icon)
382 } else {
383 item
384 }
385 })
386 .selected(selected)
387 .child(highlighted_location.render(cx)),
388 )
389 }
390
391 fn selected_as_query(&self) -> Option<String> {
392 let task_index = self.matches.get(self.selected_index())?.candidate_id;
393 let tasks = self.candidates.as_ref()?;
394 let (_, task) = tasks.get(task_index)?;
395 Some(task.resolved.as_ref()?.command_label.clone())
396 }
397
398 fn confirm_input(&mut self, omit_history_entry: bool, cx: &mut ViewContext<Picker<Self>>) {
399 let Some((task_source_kind, task)) = self.spawn_oneshot() else {
400 return;
401 };
402 self.workspace
403 .update(cx, |workspace, cx| {
404 schedule_resolved_task(workspace, task_source_kind, task, omit_history_entry, cx);
405 })
406 .ok();
407 cx.emit(DismissEvent);
408 }
409
410 fn separators_after_indices(&self) -> Vec<usize> {
411 if let Some(i) = self.last_used_candidate_index {
412 vec![i]
413 } else {
414 Vec::new()
415 }
416 }
417}
418
419#[cfg(test)]
420mod tests {
421 use std::path::PathBuf;
422
423 use editor::Editor;
424 use gpui::{TestAppContext, VisualTestContext};
425 use language::Point;
426 use project::{FakeFs, Project};
427 use serde_json::json;
428
429 use crate::modal::Spawn;
430
431 use super::*;
432
433 #[gpui::test]
434 async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
435 crate::tests::init_test(cx);
436 let fs = FakeFs::new(cx.executor());
437 fs.insert_tree(
438 "/dir",
439 json!({
440 ".zed": {
441 "tasks.json": r#"[
442 {
443 "label": "example task",
444 "command": "echo",
445 "args": ["4"]
446 },
447 {
448 "label": "another one",
449 "command": "echo",
450 "args": ["55"]
451 },
452 ]"#,
453 },
454 "a.ts": "a"
455 }),
456 )
457 .await;
458
459 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
460 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
461
462 let tasks_picker = open_spawn_tasks(&workspace, cx);
463 assert_eq!(
464 query(&tasks_picker, cx),
465 "",
466 "Initial query should be empty"
467 );
468 assert_eq!(
469 task_names(&tasks_picker, cx),
470 vec!["another one", "example task"],
471 "Initial tasks should be listed in alphabetical order"
472 );
473
474 let query_str = "tas";
475 cx.simulate_input(query_str);
476 assert_eq!(query(&tasks_picker, cx), query_str);
477 assert_eq!(
478 task_names(&tasks_picker, cx),
479 vec!["example task"],
480 "Only one task should match the query {query_str}"
481 );
482
483 cx.dispatch_action(picker::UseSelectedQuery);
484 assert_eq!(
485 query(&tasks_picker, cx),
486 "echo 4",
487 "Query should be set to the selected task's command"
488 );
489 assert_eq!(
490 task_names(&tasks_picker, cx),
491 Vec::<String>::new(),
492 "No task should be listed"
493 );
494 cx.dispatch_action(picker::ConfirmInput { secondary: false });
495
496 let tasks_picker = open_spawn_tasks(&workspace, cx);
497 assert_eq!(
498 query(&tasks_picker, cx),
499 "",
500 "Query should be reset after confirming"
501 );
502 assert_eq!(
503 task_names(&tasks_picker, cx),
504 vec!["echo 4", "another one", "example task"],
505 "New oneshot task should be listed first"
506 );
507
508 let query_str = "echo 4";
509 cx.simulate_input(query_str);
510 assert_eq!(query(&tasks_picker, cx), query_str);
511 assert_eq!(
512 task_names(&tasks_picker, cx),
513 vec!["echo 4"],
514 "New oneshot should match custom command query"
515 );
516
517 cx.dispatch_action(picker::ConfirmInput { secondary: false });
518 let tasks_picker = open_spawn_tasks(&workspace, cx);
519 assert_eq!(
520 query(&tasks_picker, cx),
521 "",
522 "Query should be reset after confirming"
523 );
524 assert_eq!(
525 task_names(&tasks_picker, cx),
526 vec![query_str, "another one", "example task"],
527 "Last recently used one show task should be listed first"
528 );
529
530 cx.dispatch_action(picker::UseSelectedQuery);
531 assert_eq!(
532 query(&tasks_picker, cx),
533 query_str,
534 "Query should be set to the custom task's name"
535 );
536 assert_eq!(
537 task_names(&tasks_picker, cx),
538 vec![query_str],
539 "Only custom task should be listed"
540 );
541
542 let query_str = "0";
543 cx.simulate_input(query_str);
544 assert_eq!(query(&tasks_picker, cx), "echo 40");
545 assert_eq!(
546 task_names(&tasks_picker, cx),
547 Vec::<String>::new(),
548 "New oneshot should not match any command query"
549 );
550
551 cx.dispatch_action(picker::ConfirmInput { secondary: true });
552 let tasks_picker = open_spawn_tasks(&workspace, cx);
553 assert_eq!(
554 query(&tasks_picker, cx),
555 "",
556 "Query should be reset after confirming"
557 );
558 assert_eq!(
559 task_names(&tasks_picker, cx),
560 vec!["echo 4", "another one", "example task"],
561 "No query should be added to the list, as it was submitted with secondary action (that maps to omit_history = true)"
562 );
563
564 cx.dispatch_action(Spawn {
565 task_name: Some("example task".to_string()),
566 });
567 let tasks_picker = workspace.update(cx, |workspace, cx| {
568 workspace
569 .active_modal::<TasksModal>(cx)
570 .unwrap()
571 .read(cx)
572 .picker
573 .clone()
574 });
575 assert_eq!(
576 task_names(&tasks_picker, cx),
577 vec!["echo 4", "another one", "example task"],
578 );
579 }
580
581 #[gpui::test]
582 async fn test_basic_context_for_simple_files(cx: &mut TestAppContext) {
583 crate::tests::init_test(cx);
584 let fs = FakeFs::new(cx.executor());
585 fs.insert_tree(
586 "/dir",
587 json!({
588 ".zed": {
589 "tasks.json": r#"[
590 {
591 "label": "hello from $ZED_FILE:$ZED_ROW:$ZED_COLUMN",
592 "command": "echo",
593 "args": ["hello", "from", "$ZED_FILE", ":", "$ZED_ROW", ":", "$ZED_COLUMN"]
594 },
595 {
596 "label": "opened now: $ZED_WORKTREE_ROOT",
597 "command": "echo",
598 "args": ["opened", "now:", "$ZED_WORKTREE_ROOT"]
599 }
600 ]"#,
601 },
602 "file_without_extension": "aaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaa",
603 "file_with.odd_extension": "b",
604 }),
605 )
606 .await;
607
608 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
609 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
610
611 let tasks_picker = open_spawn_tasks(&workspace, cx);
612 assert_eq!(
613 task_names(&tasks_picker, cx),
614 Vec::<String>::new(),
615 "Should list no file or worktree context-dependent when no file is open"
616 );
617 tasks_picker.update(cx, |_, cx| {
618 cx.emit(DismissEvent);
619 });
620 drop(tasks_picker);
621 cx.executor().run_until_parked();
622
623 let _ = workspace
624 .update(cx, |workspace, cx| {
625 workspace.open_abs_path(PathBuf::from("/dir/file_with.odd_extension"), true, cx)
626 })
627 .await
628 .unwrap();
629 cx.executor().run_until_parked();
630 let tasks_picker = open_spawn_tasks(&workspace, cx);
631 assert_eq!(
632 task_names(&tasks_picker, cx),
633 vec![
634 "hello from …th.odd_extension:1:1".to_string(),
635 "opened now: /dir".to_string()
636 ],
637 "Second opened buffer should fill the context, labels should be trimmed if long enough"
638 );
639 tasks_picker.update(cx, |_, cx| {
640 cx.emit(DismissEvent);
641 });
642 drop(tasks_picker);
643 cx.executor().run_until_parked();
644
645 let second_item = workspace
646 .update(cx, |workspace, cx| {
647 workspace.open_abs_path(PathBuf::from("/dir/file_without_extension"), true, cx)
648 })
649 .await
650 .unwrap();
651
652 let editor = cx.update(|cx| second_item.act_as::<Editor>(cx)).unwrap();
653 editor.update(cx, |editor, cx| {
654 editor.change_selections(None, cx, |s| {
655 s.select_ranges(Some(Point::new(1, 2)..Point::new(1, 5)))
656 })
657 });
658 cx.executor().run_until_parked();
659 let tasks_picker = open_spawn_tasks(&workspace, cx);
660 assert_eq!(
661 task_names(&tasks_picker, cx),
662 vec![
663 "hello from …ithout_extension:2:3".to_string(),
664 "opened now: /dir".to_string()
665 ],
666 "Opened buffer should fill the context, labels should be trimmed if long enough"
667 );
668 tasks_picker.update(cx, |_, cx| {
669 cx.emit(DismissEvent);
670 });
671 drop(tasks_picker);
672 cx.executor().run_until_parked();
673 }
674
675 fn open_spawn_tasks(
676 workspace: &View<Workspace>,
677 cx: &mut VisualTestContext,
678 ) -> View<Picker<TasksModalDelegate>> {
679 cx.dispatch_action(Spawn::default());
680 workspace.update(cx, |workspace, cx| {
681 workspace
682 .active_modal::<TasksModal>(cx)
683 .expect("no task modal after `Spawn` action was dispatched")
684 .read(cx)
685 .picker
686 .clone()
687 })
688 }
689
690 fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
691 spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
692 }
693
694 fn task_names(
695 spawn_tasks: &View<Picker<TasksModalDelegate>>,
696 cx: &mut VisualTestContext,
697 ) -> Vec<String> {
698 spawn_tasks.update(cx, |spawn_tasks, _| {
699 spawn_tasks
700 .delegate
701 .matches
702 .iter()
703 .map(|hit| hit.string.clone())
704 .collect::<Vec<_>>()
705 })
706 }
707}