modal.rs

  1use std::{path::PathBuf, sync::Arc};
  2
  3use fuzzy::{StringMatch, StringMatchCandidate};
  4use gpui::{
  5    impl_actions, rems, AppContext, DismissEvent, EventEmitter, FocusableView, InteractiveElement,
  6    Model, ParentElement, Render, SharedString, Styled, Subscription, View, ViewContext,
  7    VisualContext, WeakView,
  8};
  9use picker::{
 10    highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
 11    Picker, PickerDelegate,
 12};
 13use project::{Inventory, ProjectPath, TaskSourceKind};
 14use task::{oneshot_source::OneshotSource, Task, TaskContext};
 15use ui::{v_flex, ListItem, ListItemSpacing, RenderOnce, Selectable, WindowContext};
 16use util::{paths::PathExt, ResultExt};
 17use workspace::{ModalView, Workspace};
 18
 19use crate::schedule_task;
 20use serde::Deserialize;
 21
 22/// Spawn a task with name or open tasks modal
 23#[derive(PartialEq, Clone, Deserialize, Default)]
 24pub struct Spawn {
 25    #[serde(default)]
 26    /// Name of the task to spawn.
 27    /// If it is not set, a modal with a list of available tasks is opened instead.
 28    /// Defaults to None.
 29    pub task_name: Option<String>,
 30}
 31
 32/// Rerun last task
 33#[derive(PartialEq, Clone, Deserialize, Default)]
 34pub struct Rerun {
 35    #[serde(default)]
 36    /// Controls whether the task context is reevaluated prior to execution of a task.
 37    /// 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
 38    /// If it is, these variables will be updated to reflect current state of editor at the time task::Rerun is executed.
 39    /// default: false
 40    pub reevaluate_context: bool,
 41}
 42
 43impl_actions!(task, [Rerun, Spawn]);
 44
 45/// A modal used to spawn new tasks.
 46pub(crate) struct TasksModalDelegate {
 47    inventory: Model<Inventory>,
 48    candidates: Vec<(TaskSourceKind, Arc<dyn Task>)>,
 49    matches: Vec<StringMatch>,
 50    selected_index: usize,
 51    workspace: WeakView<Workspace>,
 52    prompt: String,
 53    task_context: TaskContext,
 54}
 55
 56impl TasksModalDelegate {
 57    fn new(
 58        inventory: Model<Inventory>,
 59        task_context: TaskContext,
 60        workspace: WeakView<Workspace>,
 61    ) -> Self {
 62        Self {
 63            inventory,
 64            workspace,
 65            candidates: Vec::new(),
 66            matches: Vec::new(),
 67            selected_index: 0,
 68            prompt: String::default(),
 69            task_context,
 70        }
 71    }
 72
 73    fn spawn_oneshot(&mut self, cx: &mut AppContext) -> Option<Arc<dyn Task>> {
 74        self.inventory
 75            .update(cx, |inventory, _| inventory.source::<OneshotSource>())?
 76            .update(cx, |oneshot_source, _| {
 77                Some(
 78                    oneshot_source
 79                        .as_any()
 80                        .downcast_mut::<OneshotSource>()?
 81                        .spawn(self.prompt.clone()),
 82                )
 83            })
 84    }
 85
 86    fn active_item_path(
 87        &mut self,
 88        cx: &mut ViewContext<'_, Picker<Self>>,
 89    ) -> Option<(PathBuf, ProjectPath)> {
 90        let workspace = self.workspace.upgrade()?.read(cx);
 91        let project = workspace.project().read(cx);
 92        let active_item = workspace.active_item(cx)?;
 93        active_item.project_path(cx).and_then(|project_path| {
 94            project
 95                .worktree_for_id(project_path.worktree_id, cx)
 96                .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path))
 97                .zip(Some(project_path))
 98        })
 99    }
100}
101
102pub(crate) struct TasksModal {
103    picker: View<Picker<TasksModalDelegate>>,
104    _subscription: Subscription,
105}
106
107impl TasksModal {
108    pub(crate) fn new(
109        inventory: Model<Inventory>,
110        task_context: TaskContext,
111        workspace: WeakView<Workspace>,
112        cx: &mut ViewContext<Self>,
113    ) -> Self {
114        let picker = cx.new_view(|cx| {
115            Picker::uniform_list(
116                TasksModalDelegate::new(inventory, task_context, workspace),
117                cx,
118            )
119        });
120        let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
121            cx.emit(DismissEvent);
122        });
123        Self {
124            picker,
125            _subscription,
126        }
127    }
128}
129
130impl Render for TasksModal {
131    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl gpui::prelude::IntoElement {
132        v_flex()
133            .key_context("TasksModal")
134            .w(rems(34.))
135            .child(self.picker.clone())
136            .on_mouse_down_out(cx.listener(|modal, _, cx| {
137                modal.picker.update(cx, |picker, cx| {
138                    picker.cancel(&Default::default(), cx);
139                })
140            }))
141    }
142}
143
144impl EventEmitter<DismissEvent> for TasksModal {}
145
146impl FocusableView for TasksModal {
147    fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
148        self.picker.read(cx).focus_handle(cx)
149    }
150}
151
152impl ModalView for TasksModal {}
153
154impl PickerDelegate for TasksModalDelegate {
155    type ListItem = ListItem;
156
157    fn match_count(&self) -> usize {
158        self.matches.len()
159    }
160
161    fn selected_index(&self) -> usize {
162        self.selected_index
163    }
164
165    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<picker::Picker<Self>>) {
166        self.selected_index = ix;
167    }
168
169    fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
170        Arc::from(format!(
171            "{} use task name as prompt, {} spawns a bash-like task from the prompt, {} runs the selected task",
172            cx.keystroke_text_for(&menu::UseSelectedQuery),
173            cx.keystroke_text_for(&menu::SecondaryConfirm),
174            cx.keystroke_text_for(&menu::Confirm),
175        ))
176    }
177
178    fn update_matches(
179        &mut self,
180        query: String,
181        cx: &mut ViewContext<picker::Picker<Self>>,
182    ) -> gpui::Task<()> {
183        cx.spawn(move |picker, mut cx| async move {
184            let Some(candidates) = picker
185                .update(&mut cx, |picker, cx| {
186                    let (path, worktree) = match picker.delegate.active_item_path(cx) {
187                        Some((abs_path, project_path)) => {
188                            (Some(abs_path), Some(project_path.worktree_id))
189                        }
190                        None => (None, None),
191                    };
192                    picker.delegate.candidates =
193                        picker.delegate.inventory.update(cx, |inventory, cx| {
194                            inventory.list_tasks(path.as_deref(), worktree, true, cx)
195                        });
196                    picker
197                        .delegate
198                        .candidates
199                        .iter()
200                        .enumerate()
201                        .map(|(index, (_, candidate))| StringMatchCandidate {
202                            id: index,
203                            char_bag: candidate.name().chars().collect(),
204                            string: candidate.name().into(),
205                        })
206                        .collect::<Vec<_>>()
207                })
208                .ok()
209            else {
210                return;
211            };
212            let matches = fuzzy::match_strings(
213                &candidates,
214                &query,
215                true,
216                1000,
217                &Default::default(),
218                cx.background_executor().clone(),
219            )
220            .await;
221            picker
222                .update(&mut cx, |picker, _| {
223                    let delegate = &mut picker.delegate;
224                    delegate.matches = matches;
225                    delegate.prompt = query;
226
227                    if delegate.matches.is_empty() {
228                        delegate.selected_index = 0;
229                    } else {
230                        delegate.selected_index =
231                            delegate.selected_index.min(delegate.matches.len() - 1);
232                    }
233                })
234                .log_err();
235        })
236    }
237
238    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<picker::Picker<Self>>) {
239        let current_match_index = self.selected_index();
240        let task = if secondary {
241            if !self.prompt.trim().is_empty() {
242                self.spawn_oneshot(cx)
243            } else {
244                None
245            }
246        } else {
247            self.matches.get(current_match_index).map(|current_match| {
248                let ix = current_match.candidate_id;
249                self.candidates[ix].1.clone()
250            })
251        };
252
253        let Some(task) = task else {
254            return;
255        };
256
257        self.workspace
258            .update(cx, |workspace, cx| {
259                schedule_task(workspace, task.as_ref(), self.task_context.clone(), cx);
260            })
261            .ok();
262        cx.emit(DismissEvent);
263    }
264
265    fn dismissed(&mut self, cx: &mut ViewContext<picker::Picker<Self>>) {
266        cx.emit(DismissEvent);
267    }
268
269    fn render_match(
270        &self,
271        ix: usize,
272        selected: bool,
273        cx: &mut ViewContext<picker::Picker<Self>>,
274    ) -> Option<Self::ListItem> {
275        let hit = &self.matches[ix];
276        let (source_kind, _) = &self.candidates[hit.candidate_id];
277        let details = match source_kind {
278            TaskSourceKind::UserInput => "user input".to_string(),
279            TaskSourceKind::Worktree { abs_path, .. } | TaskSourceKind::AbsPath(abs_path) => {
280                abs_path.compact().to_string_lossy().to_string()
281            }
282        };
283
284        let highlighted_location = HighlightedMatchWithPaths {
285            match_label: HighlightedText {
286                text: hit.string.clone(),
287                highlight_positions: hit.positions.clone(),
288                char_count: hit.string.chars().count(),
289            },
290            paths: vec![HighlightedText {
291                char_count: details.chars().count(),
292                highlight_positions: Vec::new(),
293                text: details,
294            }],
295        };
296        Some(
297            ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
298                .inset(true)
299                .spacing(ListItemSpacing::Sparse)
300                .selected(selected)
301                .child(highlighted_location.render(cx)),
302        )
303    }
304
305    fn selected_as_query(&self) -> Option<String> {
306        Some(self.matches.get(self.selected_index())?.string.clone())
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use gpui::{TestAppContext, VisualTestContext};
313    use project::{FakeFs, Project};
314    use serde_json::json;
315
316    use super::*;
317
318    #[gpui::test]
319    async fn test_spawn_tasks_modal_query_reuse(cx: &mut TestAppContext) {
320        crate::tests::init_test(cx);
321        let fs = FakeFs::new(cx.executor());
322        fs.insert_tree(
323            "/dir",
324            json!({
325                ".zed": {
326                    "tasks.json": r#"[
327                        {
328                            "label": "example task",
329                            "command": "echo",
330                            "args": ["4"]
331                        },
332                        {
333                            "label": "another one",
334                            "command": "echo",
335                            "args": ["55"]
336                        },
337                    ]"#,
338                },
339                "a.ts": "a"
340            }),
341        )
342        .await;
343
344        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
345        project.update(cx, |project, cx| {
346            project.task_inventory().update(cx, |inventory, cx| {
347                inventory.add_source(TaskSourceKind::UserInput, |cx| OneshotSource::new(cx), cx)
348            })
349        });
350
351        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
352
353        let tasks_picker = open_spawn_tasks(&workspace, cx);
354        assert_eq!(
355            query(&tasks_picker, cx),
356            "",
357            "Initial query should be empty"
358        );
359        assert_eq!(
360            task_names(&tasks_picker, cx),
361            vec!["another one", "example task"],
362            "Initial tasks should be listed in alphabetical order"
363        );
364
365        let query_str = "tas";
366        cx.simulate_input(query_str);
367        assert_eq!(query(&tasks_picker, cx), query_str);
368        assert_eq!(
369            task_names(&tasks_picker, cx),
370            vec!["example task"],
371            "Only one task should match the query {query_str}"
372        );
373
374        cx.dispatch_action(menu::UseSelectedQuery);
375        assert_eq!(
376            query(&tasks_picker, cx),
377            "example task",
378            "Query should be set to the selected task's name"
379        );
380        assert_eq!(
381            task_names(&tasks_picker, cx),
382            vec!["example task"],
383            "No other tasks should be listed"
384        );
385        cx.dispatch_action(menu::Confirm);
386
387        let tasks_picker = open_spawn_tasks(&workspace, cx);
388        assert_eq!(
389            query(&tasks_picker, cx),
390            "",
391            "Query should be reset after confirming"
392        );
393        assert_eq!(
394            task_names(&tasks_picker, cx),
395            vec!["example task", "another one"],
396            "Last recently used task should be listed first"
397        );
398
399        let query_str = "echo 4";
400        cx.simulate_input(query_str);
401        assert_eq!(query(&tasks_picker, cx), query_str);
402        assert_eq!(
403            task_names(&tasks_picker, cx),
404            Vec::<String>::new(),
405            "No tasks should match custom command query"
406        );
407
408        cx.dispatch_action(menu::SecondaryConfirm);
409        let tasks_picker = open_spawn_tasks(&workspace, cx);
410        assert_eq!(
411            query(&tasks_picker, cx),
412            "",
413            "Query should be reset after confirming"
414        );
415        assert_eq!(
416            task_names(&tasks_picker, cx),
417            vec![query_str, "example task", "another one"],
418            "Last recently used one show task should be listed first"
419        );
420
421        cx.dispatch_action(menu::UseSelectedQuery);
422        assert_eq!(
423            query(&tasks_picker, cx),
424            query_str,
425            "Query should be set to the custom task's name"
426        );
427        assert_eq!(
428            task_names(&tasks_picker, cx),
429            vec![query_str],
430            "Only custom task should be listed"
431        );
432    }
433
434    fn open_spawn_tasks(
435        workspace: &View<Workspace>,
436        cx: &mut VisualTestContext,
437    ) -> View<Picker<TasksModalDelegate>> {
438        cx.dispatch_action(crate::modal::Spawn::default());
439        workspace.update(cx, |workspace, cx| {
440            workspace
441                .active_modal::<TasksModal>(cx)
442                .unwrap()
443                .read(cx)
444                .picker
445                .clone()
446        })
447    }
448
449    fn query(spawn_tasks: &View<Picker<TasksModalDelegate>>, cx: &mut VisualTestContext) -> String {
450        spawn_tasks.update(cx, |spawn_tasks, cx| spawn_tasks.query(cx))
451    }
452
453    fn task_names(
454        spawn_tasks: &View<Picker<TasksModalDelegate>>,
455        cx: &mut VisualTestContext,
456    ) -> Vec<String> {
457        spawn_tasks.update(cx, |spawn_tasks, _| {
458            spawn_tasks
459                .delegate
460                .matches
461                .iter()
462                .map(|hit| hit.string.clone())
463                .collect::<Vec<_>>()
464        })
465    }
466}