modal.rs

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