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.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            template.label.clone()
311        } else {
312            String::new()
313        };
314        if let Some(resolved_command) = resolved_task.resolved_command() {
315            if display_label != resolved_command {
316                if !tooltip_label_text.trim().is_empty() {
317                    tooltip_label_text.push('\n');
318                }
319                tooltip_label_text.push_str(&resolved_command);
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        task.resolved_command()
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 gpui::{TestAppContext, VisualTestContext};
422    use project::{FakeFs, Project};
423    use serde_json::json;
424
425    use crate::modal::Spawn;
426
427    use super::*;
428
429    #[gpui::test]
430    async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
431        crate::tests::init_test(cx);
432        let fs = FakeFs::new(cx.executor());
433        fs.insert_tree(
434            "/dir",
435            json!({
436                ".zed": {
437                    "tasks.json": r#"[
438                        {
439                            "label": "example task",
440                            "command": "echo",
441                            "args": ["4"]
442                        },
443                        {
444                            "label": "another one",
445                            "command": "echo",
446                            "args": ["55"]
447                        },
448                    ]"#,
449                },
450                "a.ts": "a"
451            }),
452        )
453        .await;
454
455        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
456        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
457
458        let tasks_picker = open_spawn_tasks(&workspace, cx);
459        assert_eq!(
460            query(&tasks_picker, cx),
461            "",
462            "Initial query should be empty"
463        );
464        assert_eq!(
465            task_names(&tasks_picker, cx),
466            vec!["another one", "example task"],
467            "Initial tasks should be listed in alphabetical order"
468        );
469
470        let query_str = "tas";
471        cx.simulate_input(query_str);
472        assert_eq!(query(&tasks_picker, cx), query_str);
473        assert_eq!(
474            task_names(&tasks_picker, cx),
475            vec!["example task"],
476            "Only one task should match the query {query_str}"
477        );
478
479        cx.dispatch_action(picker::UseSelectedQuery);
480        assert_eq!(
481            query(&tasks_picker, cx),
482            "echo 4",
483            "Query should be set to the selected task's command"
484        );
485        assert_eq!(
486            task_names(&tasks_picker, cx),
487            Vec::<String>::new(),
488            "No task should be listed"
489        );
490        cx.dispatch_action(picker::ConfirmInput { secondary: false });
491
492        let tasks_picker = open_spawn_tasks(&workspace, cx);
493        assert_eq!(
494            query(&tasks_picker, cx),
495            "",
496            "Query should be reset after confirming"
497        );
498        assert_eq!(
499            task_names(&tasks_picker, cx),
500            vec!["echo 4", "another one", "example task"],
501            "New oneshot task should be listed first"
502        );
503
504        let query_str = "echo 4";
505        cx.simulate_input(query_str);
506        assert_eq!(query(&tasks_picker, cx), query_str);
507        assert_eq!(
508            task_names(&tasks_picker, cx),
509            vec!["echo 4"],
510            "New oneshot should match custom command query"
511        );
512
513        cx.dispatch_action(picker::ConfirmInput { secondary: false });
514        let tasks_picker = open_spawn_tasks(&workspace, cx);
515        assert_eq!(
516            query(&tasks_picker, cx),
517            "",
518            "Query should be reset after confirming"
519        );
520        assert_eq!(
521            task_names(&tasks_picker, cx),
522            vec![query_str, "another one", "example task"],
523            "Last recently used one show task should be listed first"
524        );
525
526        cx.dispatch_action(picker::UseSelectedQuery);
527        assert_eq!(
528            query(&tasks_picker, cx),
529            query_str,
530            "Query should be set to the custom task's name"
531        );
532        assert_eq!(
533            task_names(&tasks_picker, cx),
534            vec![query_str],
535            "Only custom task should be listed"
536        );
537
538        let query_str = "0";
539        cx.simulate_input(query_str);
540        assert_eq!(query(&tasks_picker, cx), "echo 40");
541        assert_eq!(
542            task_names(&tasks_picker, cx),
543            Vec::<String>::new(),
544            "New oneshot should not match any command query"
545        );
546
547        cx.dispatch_action(picker::ConfirmInput { secondary: true });
548        let tasks_picker = open_spawn_tasks(&workspace, cx);
549        assert_eq!(
550            query(&tasks_picker, cx),
551            "",
552            "Query should be reset after confirming"
553        );
554        assert_eq!(
555            task_names(&tasks_picker, cx),
556            vec!["echo 4", "another one", "example task"],
557            "No query should be added to the list, as it was submitted with secondary action (that maps to omit_history = true)"
558        );
559
560        cx.dispatch_action(Spawn {
561            task_name: Some("example task".to_string()),
562        });
563        let tasks_picker = workspace.update(cx, |workspace, cx| {
564            workspace
565                .active_modal::<TasksModal>(cx)
566                .unwrap()
567                .read(cx)
568                .picker
569                .clone()
570        });
571        assert_eq!(
572            task_names(&tasks_picker, cx),
573            vec!["echo 4", "another one", "example task"],
574        );
575    }
576
577    fn open_spawn_tasks(
578        workspace: &View<Workspace>,
579        cx: &mut VisualTestContext,
580    ) -> View<Picker<TasksModalDelegate>> {
581        cx.dispatch_action(Spawn::default());
582        workspace.update(cx, |workspace, cx| {
583            workspace
584                .active_modal::<TasksModal>(cx)
585                .unwrap()
586                .read(cx)
587                .picker
588                .clone()
589        })
590    }
591
592    fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
593        spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
594    }
595
596    fn task_names(
597        spawn_tasks: &View<Picker<TasksModalDelegate>>,
598        cx: &mut VisualTestContext,
599    ) -> Vec<String> {
600        spawn_tasks.update(cx, |spawn_tasks, _| {
601            spawn_tasks
602                .delegate
603                .matches
604                .iter()
605                .map(|hit| hit.string.clone())
606                .collect::<Vec<_>>()
607        })
608    }
609}