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, _) = &candidates.get(hit.candidate_id)?;
310
311        let highlighted_location = HighlightedText {
312            text: hit.string.clone(),
313            highlight_positions: hit.positions.clone(),
314            char_count: hit.string.chars().count(),
315        };
316        let icon = match source_kind {
317            TaskSourceKind::UserInput => Some(Icon::new(IconName::Terminal)),
318            TaskSourceKind::AbsPath { .. } => Some(Icon::new(IconName::Settings)),
319            TaskSourceKind::Worktree { .. } => Some(Icon::new(IconName::FileTree)),
320            TaskSourceKind::Language { name } => file_icons::FileIcons::get(cx)
321                .get_type_icon(&name.to_lowercase())
322                .map(|icon_path| Icon::from_path(icon_path)),
323        };
324        Some(
325            ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
326                .inset(true)
327                .spacing(ListItemSpacing::Sparse)
328                .map(|item| {
329                    let item = if matches!(source_kind, TaskSourceKind::UserInput)
330                        || Some(ix) <= self.last_used_candidate_index
331                    {
332                        let task_index = hit.candidate_id;
333                        let delete_button = div().child(
334                            IconButton::new("delete", IconName::Close)
335                                .shape(IconButtonShape::Square)
336                                .icon_color(Color::Muted)
337                                .size(ButtonSize::None)
338                                .icon_size(IconSize::XSmall)
339                                .on_click(cx.listener(move |picker, _event, cx| {
340                                    cx.stop_propagation();
341                                    cx.prevent_default();
342
343                                    picker.delegate.delete_previously_used(task_index, cx);
344                                    picker.delegate.last_used_candidate_index = picker
345                                        .delegate
346                                        .last_used_candidate_index
347                                        .unwrap_or(0)
348                                        .checked_sub(1);
349                                    picker.refresh(cx);
350                                }))
351                                .tooltip(|cx| {
352                                    Tooltip::text("Delete previously scheduled task", cx)
353                                }),
354                        );
355                        item.end_hover_slot(delete_button)
356                    } else {
357                        item
358                    };
359                    if let Some(icon) = icon {
360                        item.end_slot(icon)
361                    } else {
362                        item
363                    }
364                })
365                .selected(selected)
366                .child(highlighted_location.render(cx)),
367        )
368    }
369
370    fn selected_as_query(&self) -> Option<String> {
371        use itertools::intersperse;
372        let task_index = self.matches.get(self.selected_index())?.candidate_id;
373        let tasks = self.candidates.as_ref()?;
374        let (_, task) = tasks.get(task_index)?;
375        task.resolved.as_ref().map(|spawn_in_terminal| {
376            let mut command = spawn_in_terminal.command.clone();
377            if !spawn_in_terminal.args.is_empty() {
378                command.push(' ');
379                command.extend(intersperse(spawn_in_terminal.args.clone(), " ".to_string()));
380            }
381            command
382        })
383    }
384
385    fn confirm_input(&mut self, omit_history_entry: bool, cx: &mut ViewContext<Picker<Self>>) {
386        let Some((task_source_kind, task)) = self.spawn_oneshot() else {
387            return;
388        };
389        self.workspace
390            .update(cx, |workspace, cx| {
391                schedule_resolved_task(workspace, task_source_kind, task, omit_history_entry, cx);
392            })
393            .ok();
394        cx.emit(DismissEvent);
395    }
396
397    fn separators_after_indices(&self) -> Vec<usize> {
398        if let Some(i) = self.last_used_candidate_index {
399            vec![i]
400        } else {
401            Vec::new()
402        }
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use gpui::{TestAppContext, VisualTestContext};
409    use project::{FakeFs, Project};
410    use serde_json::json;
411
412    use crate::modal::Spawn;
413
414    use super::*;
415
416    #[gpui::test]
417    async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
418        crate::tests::init_test(cx);
419        let fs = FakeFs::new(cx.executor());
420        fs.insert_tree(
421            "/dir",
422            json!({
423                ".zed": {
424                    "tasks.json": r#"[
425                        {
426                            "label": "example task",
427                            "command": "echo",
428                            "args": ["4"]
429                        },
430                        {
431                            "label": "another one",
432                            "command": "echo",
433                            "args": ["55"]
434                        },
435                    ]"#,
436                },
437                "a.ts": "a"
438            }),
439        )
440        .await;
441
442        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
443        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
444
445        let tasks_picker = open_spawn_tasks(&workspace, cx);
446        assert_eq!(
447            query(&tasks_picker, cx),
448            "",
449            "Initial query should be empty"
450        );
451        assert_eq!(
452            task_names(&tasks_picker, cx),
453            vec!["another one", "example task"],
454            "Initial tasks should be listed in alphabetical order"
455        );
456
457        let query_str = "tas";
458        cx.simulate_input(query_str);
459        assert_eq!(query(&tasks_picker, cx), query_str);
460        assert_eq!(
461            task_names(&tasks_picker, cx),
462            vec!["example task"],
463            "Only one task should match the query {query_str}"
464        );
465
466        cx.dispatch_action(picker::UseSelectedQuery);
467        assert_eq!(
468            query(&tasks_picker, cx),
469            "echo 4",
470            "Query should be set to the selected task's command"
471        );
472        assert_eq!(
473            task_names(&tasks_picker, cx),
474            Vec::<String>::new(),
475            "No task should be listed"
476        );
477        cx.dispatch_action(picker::ConfirmInput { secondary: false });
478
479        let tasks_picker = open_spawn_tasks(&workspace, cx);
480        assert_eq!(
481            query(&tasks_picker, cx),
482            "",
483            "Query should be reset after confirming"
484        );
485        assert_eq!(
486            task_names(&tasks_picker, cx),
487            vec!["echo 4", "another one", "example task"],
488            "New oneshot task should be listed first"
489        );
490
491        let query_str = "echo 4";
492        cx.simulate_input(query_str);
493        assert_eq!(query(&tasks_picker, cx), query_str);
494        assert_eq!(
495            task_names(&tasks_picker, cx),
496            vec!["echo 4"],
497            "New oneshot should match custom command query"
498        );
499
500        cx.dispatch_action(picker::ConfirmInput { secondary: false });
501        let tasks_picker = open_spawn_tasks(&workspace, cx);
502        assert_eq!(
503            query(&tasks_picker, cx),
504            "",
505            "Query should be reset after confirming"
506        );
507        assert_eq!(
508            task_names(&tasks_picker, cx),
509            vec![query_str, "another one", "example task"],
510            "Last recently used one show task should be listed first"
511        );
512
513        cx.dispatch_action(picker::UseSelectedQuery);
514        assert_eq!(
515            query(&tasks_picker, cx),
516            query_str,
517            "Query should be set to the custom task's name"
518        );
519        assert_eq!(
520            task_names(&tasks_picker, cx),
521            vec![query_str],
522            "Only custom task should be listed"
523        );
524
525        let query_str = "0";
526        cx.simulate_input(query_str);
527        assert_eq!(query(&tasks_picker, cx), "echo 40");
528        assert_eq!(
529            task_names(&tasks_picker, cx),
530            Vec::<String>::new(),
531            "New oneshot should not match any command query"
532        );
533
534        cx.dispatch_action(picker::ConfirmInput { secondary: true });
535        let tasks_picker = open_spawn_tasks(&workspace, cx);
536        assert_eq!(
537            query(&tasks_picker, cx),
538            "",
539            "Query should be reset after confirming"
540        );
541        assert_eq!(
542            task_names(&tasks_picker, cx),
543            vec!["echo 4", "another one", "example task"],
544            "No query should be added to the list, as it was submitted with secondary action (that maps to omit_history = true)"
545        );
546
547        cx.dispatch_action(Spawn {
548            task_name: Some("example task".to_string()),
549        });
550        let tasks_picker = workspace.update(cx, |workspace, cx| {
551            workspace
552                .active_modal::<TasksModal>(cx)
553                .unwrap()
554                .read(cx)
555                .picker
556                .clone()
557        });
558        assert_eq!(
559            task_names(&tasks_picker, cx),
560            vec!["echo 4", "another one", "example task"],
561        );
562    }
563
564    fn open_spawn_tasks(
565        workspace: &View<Workspace>,
566        cx: &mut VisualTestContext,
567    ) -> View<Picker<TasksModalDelegate>> {
568        cx.dispatch_action(Spawn::default());
569        workspace.update(cx, |workspace, cx| {
570            workspace
571                .active_modal::<TasksModal>(cx)
572                .unwrap()
573                .read(cx)
574                .picker
575                .clone()
576        })
577    }
578
579    fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
580        spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
581    }
582
583    fn task_names(
584        spawn_tasks: &View<Picker<TasksModalDelegate>>,
585        cx: &mut VisualTestContext,
586    ) -> Vec<String> {
587        spawn_tasks.update(cx, |spawn_tasks, _| {
588            spawn_tasks
589                .delegate
590                .matches
591                .iter()
592                .map(|hit| hit.string.clone())
593                .collect::<Vec<_>>()
594        })
595    }
596}