modal.rs

  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
237                                .resolved
238                                .as_ref()
239                                .map(|resolved| resolved.label.clone())
240                                .unwrap_or_else(|| candidate.resolved_label.clone()),
241                        })
242                        .collect::<Vec<_>>()
243                })
244                .ok()
245            else {
246                return;
247            };
248            let matches = fuzzy::match_strings(
249                &candidates,
250                &query,
251                true,
252                1000,
253                &Default::default(),
254                cx.background_executor().clone(),
255            )
256            .await;
257            picker
258                .update(&mut cx, |picker, _| {
259                    let delegate = &mut picker.delegate;
260                    delegate.matches = matches;
261                    delegate.prompt = query;
262
263                    if delegate.matches.is_empty() {
264                        delegate.selected_index = 0;
265                    } else {
266                        delegate.selected_index =
267                            delegate.selected_index.min(delegate.matches.len() - 1);
268                    }
269                })
270                .log_err();
271        })
272    }
273
274    fn confirm(&mut self, omit_history_entry: bool, cx: &mut ViewContext<picker::Picker<Self>>) {
275        let current_match_index = self.selected_index();
276        let task = self
277            .matches
278            .get(current_match_index)
279            .and_then(|current_match| {
280                let ix = current_match.candidate_id;
281                self.candidates
282                    .as_ref()
283                    .map(|candidates| candidates[ix].clone())
284            });
285        let Some((task_source_kind, task)) = task else {
286            return;
287        };
288
289        self.workspace
290            .update(cx, |workspace, cx| {
291                schedule_resolved_task(workspace, task_source_kind, task, omit_history_entry, cx);
292            })
293            .ok();
294        cx.emit(DismissEvent);
295    }
296
297    fn dismissed(&mut self, cx: &mut ViewContext<picker::Picker<Self>>) {
298        cx.emit(DismissEvent);
299    }
300
301    fn render_match(
302        &self,
303        ix: usize,
304        selected: bool,
305        cx: &mut ViewContext<picker::Picker<Self>>,
306    ) -> Option<Self::ListItem> {
307        let candidates = self.candidates.as_ref()?;
308        let hit = &self.matches[ix];
309        let (source_kind, resolved_task) = &candidates.get(hit.candidate_id)?;
310        let template = resolved_task.original_task();
311        let display_label = resolved_task.display_label();
312
313        let mut tooltip_label_text = if display_label != &template.label {
314            resolved_task.resolved_label.clone()
315        } else {
316            String::new()
317        };
318        if let Some(resolved) = resolved_task.resolved.as_ref() {
319            if resolved.command_label != display_label
320                && resolved.command_label != resolved_task.resolved_label
321            {
322                if !tooltip_label_text.trim().is_empty() {
323                    tooltip_label_text.push('\n');
324                }
325                tooltip_label_text.push_str(&resolved.command_label);
326            }
327        }
328        let tooltip_label = if tooltip_label_text.trim().is_empty() {
329            None
330        } else {
331            Some(Tooltip::text(tooltip_label_text, cx))
332        };
333
334        let highlighted_location = HighlightedText {
335            text: hit.string.clone(),
336            highlight_positions: hit.positions.clone(),
337            char_count: hit.string.chars().count(),
338        };
339        let icon = match source_kind {
340            TaskSourceKind::UserInput => Some(Icon::new(IconName::Terminal)),
341            TaskSourceKind::AbsPath { .. } => Some(Icon::new(IconName::Settings)),
342            TaskSourceKind::Worktree { .. } => Some(Icon::new(IconName::FileTree)),
343            TaskSourceKind::Language { name } => file_icons::FileIcons::get(cx)
344                .get_type_icon(&name.to_lowercase())
345                .map(|icon_path| Icon::from_path(icon_path)),
346        };
347        Some(
348            ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
349                .inset(true)
350                .spacing(ListItemSpacing::Sparse)
351                .when_some(tooltip_label, |list_item, item_label| {
352                    list_item.tooltip(move |_| item_label.clone())
353                })
354                .map(|item| {
355                    let item = if matches!(source_kind, TaskSourceKind::UserInput)
356                        || Some(ix) <= self.last_used_candidate_index
357                    {
358                        let task_index = hit.candidate_id;
359                        let delete_button = div().child(
360                            IconButton::new("delete", IconName::Close)
361                                .shape(IconButtonShape::Square)
362                                .icon_color(Color::Muted)
363                                .size(ButtonSize::None)
364                                .icon_size(IconSize::XSmall)
365                                .on_click(cx.listener(move |picker, _event, cx| {
366                                    cx.stop_propagation();
367                                    cx.prevent_default();
368
369                                    picker.delegate.delete_previously_used(task_index, cx);
370                                    picker.delegate.last_used_candidate_index = picker
371                                        .delegate
372                                        .last_used_candidate_index
373                                        .unwrap_or(0)
374                                        .checked_sub(1);
375                                    picker.refresh(cx);
376                                }))
377                                .tooltip(|cx| {
378                                    Tooltip::text("Delete previously scheduled task", cx)
379                                }),
380                        );
381                        item.end_hover_slot(delete_button)
382                    } else {
383                        item
384                    };
385                    if let Some(icon) = icon {
386                        item.end_slot(icon)
387                    } else {
388                        item
389                    }
390                })
391                .selected(selected)
392                .child(highlighted_location.render(cx)),
393        )
394    }
395
396    fn selected_as_query(&self) -> Option<String> {
397        let task_index = self.matches.get(self.selected_index())?.candidate_id;
398        let tasks = self.candidates.as_ref()?;
399        let (_, task) = tasks.get(task_index)?;
400        Some(task.resolved.as_ref()?.command_label.clone())
401    }
402
403    fn confirm_input(&mut self, omit_history_entry: bool, cx: &mut ViewContext<Picker<Self>>) {
404        let Some((task_source_kind, task)) = self.spawn_oneshot() else {
405            return;
406        };
407        self.workspace
408            .update(cx, |workspace, cx| {
409                schedule_resolved_task(workspace, task_source_kind, task, omit_history_entry, cx);
410            })
411            .ok();
412        cx.emit(DismissEvent);
413    }
414
415    fn separators_after_indices(&self) -> Vec<usize> {
416        if let Some(i) = self.last_used_candidate_index {
417            vec![i]
418        } else {
419            Vec::new()
420        }
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use std::{path::PathBuf, sync::Arc};
427
428    use editor::Editor;
429    use gpui::{TestAppContext, VisualTestContext};
430    use language::{ContextProviderWithTasks, Language, LanguageConfig, LanguageMatcher, Point};
431    use project::{FakeFs, Project};
432    use serde_json::json;
433    use task::TaskTemplates;
434    use workspace::CloseInactiveTabsAndPanes;
435
436    use crate::{modal::Spawn, tests::init_test};
437
438    use super::*;
439
440    #[gpui::test]
441    async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
442        init_test(cx);
443        let fs = FakeFs::new(cx.executor());
444        fs.insert_tree(
445            "/dir",
446            json!({
447                ".zed": {
448                    "tasks.json": r#"[
449                        {
450                            "label": "example task",
451                            "command": "echo",
452                            "args": ["4"]
453                        },
454                        {
455                            "label": "another one",
456                            "command": "echo",
457                            "args": ["55"]
458                        },
459                    ]"#,
460                },
461                "a.ts": "a"
462            }),
463        )
464        .await;
465
466        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
467        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
468
469        let tasks_picker = open_spawn_tasks(&workspace, cx);
470        assert_eq!(
471            query(&tasks_picker, cx),
472            "",
473            "Initial query should be empty"
474        );
475        assert_eq!(
476            task_names(&tasks_picker, cx),
477            vec!["another one", "example task"],
478            "Initial tasks should be listed in alphabetical order"
479        );
480
481        let query_str = "tas";
482        cx.simulate_input(query_str);
483        assert_eq!(query(&tasks_picker, cx), query_str);
484        assert_eq!(
485            task_names(&tasks_picker, cx),
486            vec!["example task"],
487            "Only one task should match the query {query_str}"
488        );
489
490        cx.dispatch_action(picker::UseSelectedQuery);
491        assert_eq!(
492            query(&tasks_picker, cx),
493            "echo 4",
494            "Query should be set to the selected task's command"
495        );
496        assert_eq!(
497            task_names(&tasks_picker, cx),
498            Vec::<String>::new(),
499            "No task should be listed"
500        );
501        cx.dispatch_action(picker::ConfirmInput { secondary: false });
502
503        let tasks_picker = open_spawn_tasks(&workspace, cx);
504        assert_eq!(
505            query(&tasks_picker, cx),
506            "",
507            "Query should be reset after confirming"
508        );
509        assert_eq!(
510            task_names(&tasks_picker, cx),
511            vec!["echo 4", "another one", "example task"],
512            "New oneshot task should be listed first"
513        );
514
515        let query_str = "echo 4";
516        cx.simulate_input(query_str);
517        assert_eq!(query(&tasks_picker, cx), query_str);
518        assert_eq!(
519            task_names(&tasks_picker, cx),
520            vec!["echo 4"],
521            "New oneshot should match custom command query"
522        );
523
524        cx.dispatch_action(picker::ConfirmInput { secondary: false });
525        let tasks_picker = open_spawn_tasks(&workspace, cx);
526        assert_eq!(
527            query(&tasks_picker, cx),
528            "",
529            "Query should be reset after confirming"
530        );
531        assert_eq!(
532            task_names(&tasks_picker, cx),
533            vec![query_str, "another one", "example task"],
534            "Last recently used one show task should be listed first"
535        );
536
537        cx.dispatch_action(picker::UseSelectedQuery);
538        assert_eq!(
539            query(&tasks_picker, cx),
540            query_str,
541            "Query should be set to the custom task's name"
542        );
543        assert_eq!(
544            task_names(&tasks_picker, cx),
545            vec![query_str],
546            "Only custom task should be listed"
547        );
548
549        let query_str = "0";
550        cx.simulate_input(query_str);
551        assert_eq!(query(&tasks_picker, cx), "echo 40");
552        assert_eq!(
553            task_names(&tasks_picker, cx),
554            Vec::<String>::new(),
555            "New oneshot should not match any command query"
556        );
557
558        cx.dispatch_action(picker::ConfirmInput { secondary: true });
559        let tasks_picker = open_spawn_tasks(&workspace, cx);
560        assert_eq!(
561            query(&tasks_picker, cx),
562            "",
563            "Query should be reset after confirming"
564        );
565        assert_eq!(
566            task_names(&tasks_picker, cx),
567            vec!["echo 4", "another one", "example task"],
568            "No query should be added to the list, as it was submitted with secondary action (that maps to omit_history = true)"
569        );
570
571        cx.dispatch_action(Spawn {
572            task_name: Some("example task".to_string()),
573        });
574        let tasks_picker = workspace.update(cx, |workspace, cx| {
575            workspace
576                .active_modal::<TasksModal>(cx)
577                .unwrap()
578                .read(cx)
579                .picker
580                .clone()
581        });
582        assert_eq!(
583            task_names(&tasks_picker, cx),
584            vec!["echo 4", "another one", "example task"],
585        );
586    }
587
588    #[gpui::test]
589    async fn test_basic_context_for_simple_files(cx: &mut TestAppContext) {
590        init_test(cx);
591        let fs = FakeFs::new(cx.executor());
592        fs.insert_tree(
593            "/dir",
594            json!({
595                ".zed": {
596                    "tasks.json": r#"[
597                        {
598                            "label": "hello from $ZED_FILE:$ZED_ROW:$ZED_COLUMN",
599                            "command": "echo",
600                            "args": ["hello", "from", "$ZED_FILE", ":", "$ZED_ROW", ":", "$ZED_COLUMN"]
601                        },
602                        {
603                            "label": "opened now: $ZED_WORKTREE_ROOT",
604                            "command": "echo",
605                            "args": ["opened", "now:", "$ZED_WORKTREE_ROOT"]
606                        }
607                    ]"#,
608                },
609                "file_without_extension": "aaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaa",
610                "file_with.odd_extension": "b",
611            }),
612        )
613        .await;
614
615        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
616        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
617
618        let tasks_picker = open_spawn_tasks(&workspace, cx);
619        assert_eq!(
620            task_names(&tasks_picker, cx),
621            Vec::<String>::new(),
622            "Should list no file or worktree context-dependent when no file is open"
623        );
624        tasks_picker.update(cx, |_, cx| {
625            cx.emit(DismissEvent);
626        });
627        drop(tasks_picker);
628        cx.executor().run_until_parked();
629
630        let _ = workspace
631            .update(cx, |workspace, cx| {
632                workspace.open_abs_path(PathBuf::from("/dir/file_with.odd_extension"), true, cx)
633            })
634            .await
635            .unwrap();
636        cx.executor().run_until_parked();
637        let tasks_picker = open_spawn_tasks(&workspace, cx);
638        assert_eq!(
639            task_names(&tasks_picker, cx),
640            vec![
641                "hello from …th.odd_extension:1:1".to_string(),
642                "opened now: /dir".to_string()
643            ],
644            "Second opened buffer should fill the context, labels should be trimmed if long enough"
645        );
646        tasks_picker.update(cx, |_, cx| {
647            cx.emit(DismissEvent);
648        });
649        drop(tasks_picker);
650        cx.executor().run_until_parked();
651
652        let second_item = workspace
653            .update(cx, |workspace, cx| {
654                workspace.open_abs_path(PathBuf::from("/dir/file_without_extension"), true, cx)
655            })
656            .await
657            .unwrap();
658
659        let editor = cx.update(|cx| second_item.act_as::<Editor>(cx)).unwrap();
660        editor.update(cx, |editor, cx| {
661            editor.change_selections(None, cx, |s| {
662                s.select_ranges(Some(Point::new(1, 2)..Point::new(1, 5)))
663            })
664        });
665        cx.executor().run_until_parked();
666        let tasks_picker = open_spawn_tasks(&workspace, cx);
667        assert_eq!(
668            task_names(&tasks_picker, cx),
669            vec![
670                "hello from …ithout_extension:2:3".to_string(),
671                "opened now: /dir".to_string()
672            ],
673            "Opened buffer should fill the context, labels should be trimmed if long enough"
674        );
675        tasks_picker.update(cx, |_, cx| {
676            cx.emit(DismissEvent);
677        });
678        drop(tasks_picker);
679        cx.executor().run_until_parked();
680    }
681
682    #[gpui::test]
683    async fn test_language_task_filtering(cx: &mut TestAppContext) {
684        init_test(cx);
685        let fs = FakeFs::new(cx.executor());
686        fs.insert_tree(
687            "/dir",
688            json!({
689                "a1.ts": "// a1",
690                "a2.ts": "// a2",
691                "b.rs": "// b",
692            }),
693        )
694        .await;
695
696        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
697        project.read_with(cx, |project, _| {
698            let language_registry = project.languages();
699            language_registry.add(Arc::new(
700                Language::new(
701                    LanguageConfig {
702                        name: "TypeScript".into(),
703                        matcher: LanguageMatcher {
704                            path_suffixes: vec!["ts".to_string()],
705                            ..LanguageMatcher::default()
706                        },
707                        ..LanguageConfig::default()
708                    },
709                    None,
710                )
711                .with_context_provider(Some(Arc::new(
712                    ContextProviderWithTasks::new(TaskTemplates(vec![
713                        TaskTemplate {
714                            label: "Task without variables".to_string(),
715                            command: "npm run clean".to_string(),
716                            ..TaskTemplate::default()
717                        },
718                        TaskTemplate {
719                            label: "TypeScript task from file $ZED_FILE".to_string(),
720                            command: "npm run build".to_string(),
721                            ..TaskTemplate::default()
722                        },
723                        TaskTemplate {
724                            label: "Another task from file $ZED_FILE".to_string(),
725                            command: "npm run lint".to_string(),
726                            ..TaskTemplate::default()
727                        },
728                    ])),
729                ))),
730            ));
731            language_registry.add(Arc::new(
732                Language::new(
733                    LanguageConfig {
734                        name: "Rust".into(),
735                        matcher: LanguageMatcher {
736                            path_suffixes: vec!["rs".to_string()],
737                            ..LanguageMatcher::default()
738                        },
739                        ..LanguageConfig::default()
740                    },
741                    None,
742                )
743                .with_context_provider(Some(Arc::new(
744                    ContextProviderWithTasks::new(TaskTemplates(vec![TaskTemplate {
745                        label: "Rust task".to_string(),
746                        command: "cargo check".into(),
747                        ..TaskTemplate::default()
748                    }])),
749                ))),
750            ));
751        });
752        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
753
754        let _ts_file_1 = workspace
755            .update(cx, |workspace, cx| {
756                workspace.open_abs_path(PathBuf::from("/dir/a1.ts"), true, cx)
757            })
758            .await
759            .unwrap();
760        let tasks_picker = open_spawn_tasks(&workspace, cx);
761        assert_eq!(
762            task_names(&tasks_picker, cx),
763            vec![
764                "Another task from file /dir/a1.ts",
765                "TypeScript task from file /dir/a1.ts",
766                "Task without variables",
767            ],
768            "Should open spawn TypeScript tasks for the opened file, tasks with most template variables above, all groups sorted alphanumerically"
769        );
770        emulate_task_schedule(
771            tasks_picker,
772            &project,
773            "TypeScript task from file /dir/a1.ts",
774            cx,
775        );
776
777        let tasks_picker = open_spawn_tasks(&workspace, cx);
778        assert_eq!(
779            task_names(&tasks_picker, cx),
780            vec!["TypeScript task from file /dir/a1.ts", "Another task from file /dir/a1.ts", "Task without variables"],
781            "After spawning the task and getting it into the history, it should be up in the sort as recently used"
782        );
783        tasks_picker.update(cx, |_, cx| {
784            cx.emit(DismissEvent);
785        });
786        drop(tasks_picker);
787        cx.executor().run_until_parked();
788
789        let _ts_file_2 = workspace
790            .update(cx, |workspace, cx| {
791                workspace.open_abs_path(PathBuf::from("/dir/a2.ts"), true, cx)
792            })
793            .await
794            .unwrap();
795        let tasks_picker = open_spawn_tasks(&workspace, cx);
796        assert_eq!(
797            task_names(&tasks_picker, cx),
798            vec![
799                "TypeScript task from file /dir/a1.ts",
800                "Another task from file /dir/a2.ts",
801                "TypeScript task from file /dir/a2.ts",
802                "Task without variables"
803            ],
804            "Even when both TS files are open, should only show the history (on the top), and tasks, resolved for the current file"
805        );
806        tasks_picker.update(cx, |_, cx| {
807            cx.emit(DismissEvent);
808        });
809        drop(tasks_picker);
810        cx.executor().run_until_parked();
811
812        let _rs_file = workspace
813            .update(cx, |workspace, cx| {
814                workspace.open_abs_path(PathBuf::from("/dir/b.rs"), true, cx)
815            })
816            .await
817            .unwrap();
818        let tasks_picker = open_spawn_tasks(&workspace, cx);
819        assert_eq!(
820            task_names(&tasks_picker, cx),
821            vec!["Rust task"],
822            "Even when both TS files are open and one TS task spawned, opened file's language tasks should be displayed only"
823        );
824
825        cx.dispatch_action(CloseInactiveTabsAndPanes::default());
826        emulate_task_schedule(tasks_picker, &project, "Rust task", cx);
827        let _ts_file_2 = workspace
828            .update(cx, |workspace, cx| {
829                workspace.open_abs_path(PathBuf::from("/dir/a2.ts"), true, cx)
830            })
831            .await
832            .unwrap();
833        let tasks_picker = open_spawn_tasks(&workspace, cx);
834        assert_eq!(
835            task_names(&tasks_picker, cx),
836            vec![
837                "TypeScript task from file /dir/a1.ts",
838                "Another task from file /dir/a2.ts",
839                "TypeScript task from file /dir/a2.ts",
840                "Task without variables"
841            ],
842            "After closing all but *.rs tabs, running a Rust task and switching back to TS tasks, \
843            same TS spawn history should be restored"
844        );
845    }
846
847    fn emulate_task_schedule(
848        tasks_picker: View<Picker<TasksModalDelegate>>,
849        project: &Model<Project>,
850        scheduled_task_label: &str,
851        cx: &mut VisualTestContext,
852    ) {
853        let scheduled_task = tasks_picker.update(cx, |tasks_picker, _| {
854            tasks_picker
855                .delegate
856                .candidates
857                .iter()
858                .flatten()
859                .find(|(_, task)| task.resolved_label == scheduled_task_label)
860                .cloned()
861                .unwrap()
862        });
863        project.update(cx, |project, cx| {
864            project.task_inventory().update(cx, |inventory, _| {
865                let (kind, task) = scheduled_task;
866                inventory.task_scheduled(kind, task);
867            })
868        });
869        tasks_picker.update(cx, |_, cx| {
870            cx.emit(DismissEvent);
871        });
872        drop(tasks_picker);
873        cx.executor().run_until_parked()
874    }
875
876    fn open_spawn_tasks(
877        workspace: &View<Workspace>,
878        cx: &mut VisualTestContext,
879    ) -> View<Picker<TasksModalDelegate>> {
880        cx.dispatch_action(Spawn::default());
881        workspace.update(cx, |workspace, cx| {
882            workspace
883                .active_modal::<TasksModal>(cx)
884                .expect("no task modal after `Spawn` action was dispatched")
885                .read(cx)
886                .picker
887                .clone()
888        })
889    }
890
891    fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
892        spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
893    }
894
895    fn task_names(
896        spawn_tasks: &View<Picker<TasksModalDelegate>>,
897        cx: &mut VisualTestContext,
898    ) -> Vec<String> {
899        spawn_tasks.update(cx, |spawn_tasks, _| {
900            spawn_tasks
901                .delegate
902                .matches
903                .iter()
904                .map(|hit| hit.string.clone())
905                .collect::<Vec<_>>()
906        })
907    }
908}