tasks_ui.rs

  1use std::path::Path;
  2
  3use collections::HashMap;
  4use editor::Editor;
  5use gpui::{App, AppContext as _, Context, Entity, Task, Window};
  6use modal::TaskOverrides;
  7use project::{Location, TaskContexts, TaskSourceKind, Worktree};
  8use task::{RevealTarget, TaskContext, TaskId, TaskTemplate, TaskVariables, VariableName};
  9use workspace::Workspace;
 10
 11mod modal;
 12
 13pub use modal::{Rerun, ShowAttachModal, Spawn, TasksModal};
 14
 15pub fn init(cx: &mut App) {
 16    cx.observe_new(
 17        |workspace: &mut Workspace, _: Option<&mut Window>, _: &mut Context<Workspace>| {
 18            workspace
 19                .register_action(spawn_task_or_modal)
 20                .register_action(move |workspace, action: &modal::Rerun, window, cx| {
 21                    if let Some((task_source_kind, mut last_scheduled_task)) = workspace
 22                        .project()
 23                        .read(cx)
 24                        .task_store()
 25                        .read(cx)
 26                        .task_inventory()
 27                        .and_then(|inventory| {
 28                            inventory.read(cx).last_scheduled_task(
 29                                action
 30                                    .task_id
 31                                    .as_ref()
 32                                    .map(|id| TaskId(id.clone()))
 33                                    .as_ref(),
 34                            )
 35                        })
 36                    {
 37                        if action.reevaluate_context {
 38                            let mut original_task = last_scheduled_task.original_task().clone();
 39                            if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
 40                                original_task.allow_concurrent_runs = allow_concurrent_runs;
 41                            }
 42                            if let Some(use_new_terminal) = action.use_new_terminal {
 43                                original_task.use_new_terminal = use_new_terminal;
 44                            }
 45                            let task_contexts = task_contexts(workspace, window, cx);
 46                            cx.spawn_in(window, async move |workspace, cx| {
 47                                let task_contexts = task_contexts.await;
 48                                let default_context = TaskContext::default();
 49                                workspace
 50                                    .update_in(cx, |workspace, window, cx| {
 51                                        workspace.schedule_task(
 52                                            task_source_kind,
 53                                            &original_task,
 54                                            task_contexts
 55                                                .active_context()
 56                                                .unwrap_or(&default_context),
 57                                            false,
 58                                            window,
 59                                            cx,
 60                                        )
 61                                    })
 62                                    .ok()
 63                            })
 64                            .detach()
 65                        } else {
 66                            let resolved = &mut last_scheduled_task.resolved;
 67
 68                            if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
 69                                resolved.allow_concurrent_runs = allow_concurrent_runs;
 70                            }
 71                            if let Some(use_new_terminal) = action.use_new_terminal {
 72                                resolved.use_new_terminal = use_new_terminal;
 73                            }
 74
 75                            workspace.schedule_resolved_task(
 76                                task_source_kind,
 77                                last_scheduled_task,
 78                                false,
 79                                window,
 80                                cx,
 81                            );
 82                        }
 83                    } else {
 84                        toggle_modal(workspace, None, window, cx).detach();
 85                    };
 86                });
 87        },
 88    )
 89    .detach();
 90}
 91
 92fn spawn_task_or_modal(
 93    workspace: &mut Workspace,
 94    action: &Spawn,
 95    window: &mut Window,
 96    cx: &mut Context<Workspace>,
 97) {
 98    match action {
 99        Spawn::ByName {
100            task_name,
101            reveal_target,
102        } => {
103            let overrides = reveal_target.map(|reveal_target| TaskOverrides {
104                reveal_target: Some(reveal_target),
105            });
106            let name = task_name.clone();
107            spawn_tasks_filtered(move |(_, task)| task.label.eq(&name), overrides, window, cx)
108                .detach_and_log_err(cx)
109        }
110        Spawn::ByTag {
111            task_tag,
112            reveal_target,
113        } => {
114            let overrides = reveal_target.map(|reveal_target| TaskOverrides {
115                reveal_target: Some(reveal_target),
116            });
117            let tag = task_tag.clone();
118            spawn_tasks_filtered(
119                move |(_, task)| task.tags.contains(&tag),
120                overrides,
121                window,
122                cx,
123            )
124            .detach_and_log_err(cx)
125        }
126        Spawn::ViaModal { reveal_target } => {
127            toggle_modal(workspace, *reveal_target, window, cx).detach()
128        }
129    }
130}
131
132pub fn toggle_modal(
133    workspace: &mut Workspace,
134    reveal_target: Option<RevealTarget>,
135    window: &mut Window,
136    cx: &mut Context<Workspace>,
137) -> Task<()> {
138    let task_store = workspace.project().read(cx).task_store().clone();
139    let workspace_handle = workspace.weak_handle();
140    let can_open_modal = workspace.project().update(cx, |project, cx| {
141        project.is_local() || project.ssh_connection_string(cx).is_some() || project.is_via_ssh()
142    });
143    if can_open_modal {
144        let task_contexts = task_contexts(workspace, window, cx);
145        cx.spawn_in(window, async move |workspace, cx| {
146            let task_contexts = task_contexts.await;
147            workspace
148                .update_in(cx, |workspace, window, cx| {
149                    workspace.toggle_modal(window, cx, |window, cx| {
150                        TasksModal::new(
151                            task_store.clone(),
152                            task_contexts,
153                            reveal_target.map(|target| TaskOverrides {
154                                reveal_target: Some(target),
155                            }),
156                            workspace_handle,
157                            window,
158                            cx,
159                        )
160                    })
161                })
162                .ok();
163        })
164    } else {
165        Task::ready(())
166    }
167}
168
169fn spawn_tasks_filtered<F>(
170    mut predicate: F,
171    overrides: Option<TaskOverrides>,
172    window: &mut Window,
173    cx: &mut Context<Workspace>,
174) -> Task<anyhow::Result<()>>
175where
176    F: FnMut((&TaskSourceKind, &TaskTemplate)) -> bool + 'static,
177{
178    cx.spawn_in(window, async move |workspace, cx| {
179        let task_contexts = workspace.update_in(cx, |workspace, window, cx| {
180            task_contexts(workspace, window, cx)
181        })?;
182        let task_contexts = task_contexts.await;
183        let mut tasks = workspace.update(cx, |workspace, cx| {
184            let Some(task_inventory) = workspace
185                .project()
186                .read(cx)
187                .task_store()
188                .read(cx)
189                .task_inventory()
190                .cloned()
191            else {
192                return Vec::new();
193            };
194            let (file, language) = task_contexts
195                .location()
196                .map(|location| {
197                    let buffer = location.buffer.read(cx);
198                    (
199                        buffer.file().cloned(),
200                        buffer.language_at(location.range.start),
201                    )
202                })
203                .unwrap_or_default();
204            task_inventory
205                .read(cx)
206                .list_tasks(file, language, task_contexts.worktree(), cx)
207        })?;
208
209        let did_spawn = workspace
210            .update_in(cx, |workspace, window, cx| {
211                let default_context = TaskContext::default();
212                let active_context = task_contexts.active_context().unwrap_or(&default_context);
213
214                tasks.retain_mut(|(task_source_kind, target_task)| {
215                    if predicate((task_source_kind, target_task)) {
216                        if let Some(overrides) = &overrides {
217                            if let Some(target_override) = overrides.reveal_target {
218                                target_task.reveal_target = target_override;
219                            }
220                        }
221                        workspace.schedule_task(
222                            task_source_kind.clone(),
223                            target_task,
224                            active_context,
225                            false,
226                            window,
227                            cx,
228                        );
229                        true
230                    } else {
231                        false
232                    }
233                });
234
235                if tasks.is_empty() { None } else { Some(()) }
236            })?
237            .is_some();
238        if !did_spawn {
239            workspace
240                .update_in(cx, |workspace, window, cx| {
241                    spawn_task_or_modal(
242                        workspace,
243                        &Spawn::ViaModal {
244                            reveal_target: overrides.and_then(|overrides| overrides.reveal_target),
245                        },
246                        window,
247                        cx,
248                    );
249                })
250                .ok();
251        }
252
253        Ok(())
254    })
255}
256
257pub fn task_contexts(
258    workspace: &Workspace,
259    window: &mut Window,
260    cx: &mut App,
261) -> Task<TaskContexts> {
262    let active_item = workspace.active_item(cx);
263    let active_worktree = active_item
264        .as_ref()
265        .and_then(|item| item.project_path(cx))
266        .map(|project_path| project_path.worktree_id)
267        .filter(|worktree_id| {
268            workspace
269                .project()
270                .read(cx)
271                .worktree_for_id(*worktree_id, cx)
272                .map_or(false, |worktree| is_visible_directory(&worktree, cx))
273        });
274
275    let active_editor = active_item.and_then(|item| item.act_as::<Editor>(cx));
276
277    let editor_context_task = active_editor.as_ref().map(|active_editor| {
278        active_editor.update(cx, |editor, cx| editor.task_context(window, cx))
279    });
280
281    let location = active_editor.as_ref().and_then(|editor| {
282        editor.update(cx, |editor, cx| {
283            let selection = editor.selections.newest_anchor();
284            let multi_buffer = editor.buffer().clone();
285            let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
286            let (buffer_snapshot, buffer_offset) =
287                multi_buffer_snapshot.point_to_buffer_offset(selection.head())?;
288            let buffer_anchor = buffer_snapshot.anchor_before(buffer_offset);
289            let buffer = multi_buffer.read(cx).buffer(buffer_snapshot.remote_id())?;
290            Some(Location {
291                buffer,
292                range: buffer_anchor..buffer_anchor,
293            })
294        })
295    });
296
297    let lsp_task_sources = active_editor
298        .as_ref()
299        .map(|active_editor| active_editor.update(cx, |editor, cx| editor.lsp_task_sources(cx)))
300        .unwrap_or_default();
301
302    let latest_selection = active_editor.as_ref().map(|active_editor| {
303        active_editor
304            .read(cx)
305            .selections
306            .newest_anchor()
307            .head()
308            .text_anchor
309    });
310
311    let mut worktree_abs_paths = workspace
312        .worktrees(cx)
313        .filter(|worktree| is_visible_directory(worktree, cx))
314        .map(|worktree| {
315            let worktree = worktree.read(cx);
316            (worktree.id(), worktree.abs_path())
317        })
318        .collect::<HashMap<_, _>>();
319
320    cx.background_spawn(async move {
321        let mut task_contexts = TaskContexts::default();
322
323        task_contexts.lsp_task_sources = lsp_task_sources;
324        task_contexts.latest_selection = latest_selection;
325
326        if let Some(editor_context_task) = editor_context_task {
327            if let Some(editor_context) = editor_context_task.await {
328                task_contexts.active_item_context =
329                    Some((active_worktree, location, editor_context));
330            }
331        }
332
333        if let Some(active_worktree) = active_worktree {
334            if let Some(active_worktree_abs_path) = worktree_abs_paths.remove(&active_worktree) {
335                task_contexts.active_worktree_context =
336                    Some((active_worktree, worktree_context(&active_worktree_abs_path)));
337            }
338        } else if worktree_abs_paths.len() == 1 {
339            task_contexts.active_worktree_context = worktree_abs_paths
340                .drain()
341                .next()
342                .map(|(id, abs_path)| (id, worktree_context(&abs_path)));
343        }
344
345        task_contexts.other_worktree_contexts.extend(
346            worktree_abs_paths
347                .into_iter()
348                .map(|(id, abs_path)| (id, worktree_context(&abs_path))),
349        );
350        task_contexts
351    })
352}
353
354fn is_visible_directory(worktree: &Entity<Worktree>, cx: &App) -> bool {
355    let worktree = worktree.read(cx);
356    worktree.is_visible() && worktree.root_entry().map_or(false, |entry| entry.is_dir())
357}
358
359fn worktree_context(worktree_abs_path: &Path) -> TaskContext {
360    let mut task_variables = TaskVariables::default();
361    task_variables.insert(
362        VariableName::WorktreeRoot,
363        worktree_abs_path.to_string_lossy().to_string(),
364    );
365    TaskContext {
366        cwd: Some(worktree_abs_path.to_path_buf()),
367        task_variables,
368        project_env: HashMap::default(),
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use std::{collections::HashMap, sync::Arc};
375
376    use editor::Editor;
377    use gpui::TestAppContext;
378    use language::{Language, LanguageConfig};
379    use project::{BasicContextProvider, FakeFs, Project, task_store::TaskStore};
380    use serde_json::json;
381    use task::{TaskContext, TaskVariables, VariableName};
382    use ui::VisualContext;
383    use util::{path, separator};
384    use workspace::{AppState, Workspace};
385
386    use crate::task_contexts;
387
388    #[gpui::test]
389    async fn test_default_language_context(cx: &mut TestAppContext) {
390        init_test(cx);
391        let fs = FakeFs::new(cx.executor());
392        fs.insert_tree(
393            path!("/dir"),
394            json!({
395                ".zed": {
396                    "tasks.json": r#"[
397                            {
398                                "label": "example task",
399                                "command": "echo",
400                                "args": ["4"]
401                            },
402                            {
403                                "label": "another one",
404                                "command": "echo",
405                                "args": ["55"]
406                            },
407                        ]"#,
408                },
409                "a.ts": "function this_is_a_test() { }",
410                "rust": {
411                                    "b.rs": "use std; fn this_is_a_rust_file() { }",
412                }
413
414            }),
415        )
416        .await;
417        let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
418        let worktree_store = project.read_with(cx, |project, _| project.worktree_store().clone());
419        let rust_language = Arc::new(
420            Language::new(
421                LanguageConfig::default(),
422                Some(tree_sitter_rust::LANGUAGE.into()),
423            )
424            .with_outline_query(
425                r#"(function_item
426            "fn" @context
427            name: (_) @name) @item"#,
428            )
429            .unwrap()
430            .with_context_provider(Some(Arc::new(BasicContextProvider::new(
431                worktree_store.clone(),
432            )))),
433        );
434
435        let typescript_language = Arc::new(
436            Language::new(
437                LanguageConfig::default(),
438                Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
439            )
440            .with_outline_query(
441                r#"(function_declaration
442                    "async"? @context
443                    "function" @context
444                    name: (_) @name
445                    parameters: (formal_parameters
446                        "(" @context
447                        ")" @context)) @item"#,
448            )
449            .unwrap()
450            .with_context_provider(Some(Arc::new(BasicContextProvider::new(
451                worktree_store.clone(),
452            )))),
453        );
454
455        let worktree_id = project.update(cx, |project, cx| {
456            project.worktrees(cx).next().unwrap().read(cx).id()
457        });
458        let (workspace, cx) =
459            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
460
461        let buffer1 = workspace
462            .update(cx, |this, cx| {
463                this.project()
464                    .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
465            })
466            .await
467            .unwrap();
468        buffer1.update(cx, |this, cx| {
469            this.set_language(Some(typescript_language), cx)
470        });
471        let editor1 = cx.new_window_entity(|window, cx| {
472            Editor::for_buffer(buffer1, Some(project.clone()), window, cx)
473        });
474        let buffer2 = workspace
475            .update(cx, |this, cx| {
476                this.project().update(cx, |this, cx| {
477                    this.open_buffer((worktree_id, "rust/b.rs"), cx)
478                })
479            })
480            .await
481            .unwrap();
482        buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
483        let editor2 = cx
484            .new_window_entity(|window, cx| Editor::for_buffer(buffer2, Some(project), window, cx));
485
486        let first_context = workspace
487            .update_in(cx, |workspace, window, cx| {
488                workspace.add_item_to_center(Box::new(editor1.clone()), window, cx);
489                workspace.add_item_to_center(Box::new(editor2.clone()), window, cx);
490                assert_eq!(
491                    workspace.active_item(cx).unwrap().item_id(),
492                    editor2.entity_id()
493                );
494                task_contexts(workspace, window, cx)
495            })
496            .await;
497
498        assert_eq!(
499            first_context
500                .active_context()
501                .expect("Should have an active context"),
502            &TaskContext {
503                cwd: Some(path!("/dir").into()),
504                task_variables: TaskVariables::from_iter([
505                    (VariableName::File, path!("/dir/rust/b.rs").into()),
506                    (VariableName::Filename, "b.rs".into()),
507                    (VariableName::RelativeFile, separator!("rust/b.rs").into()),
508                    (VariableName::Dirname, path!("/dir/rust").into()),
509                    (VariableName::Stem, "b".into()),
510                    (VariableName::WorktreeRoot, path!("/dir").into()),
511                    (VariableName::Row, "1".into()),
512                    (VariableName::Column, "1".into()),
513                ]),
514                project_env: HashMap::default(),
515            }
516        );
517
518        // And now, let's select an identifier.
519        editor2.update_in(cx, |editor, window, cx| {
520            editor.change_selections(None, window, cx, |selections| {
521                selections.select_ranges([14..18])
522            })
523        });
524
525        assert_eq!(
526            workspace
527                .update_in(cx, |workspace, window, cx| {
528                    task_contexts(workspace, window, cx)
529                })
530                .await
531                .active_context()
532                .expect("Should have an active context"),
533            &TaskContext {
534                cwd: Some(path!("/dir").into()),
535                task_variables: TaskVariables::from_iter([
536                    (VariableName::File, path!("/dir/rust/b.rs").into()),
537                    (VariableName::Filename, "b.rs".into()),
538                    (VariableName::RelativeFile, separator!("rust/b.rs").into()),
539                    (VariableName::Dirname, path!("/dir/rust").into()),
540                    (VariableName::Stem, "b".into()),
541                    (VariableName::WorktreeRoot, path!("/dir").into()),
542                    (VariableName::Row, "1".into()),
543                    (VariableName::Column, "15".into()),
544                    (VariableName::SelectedText, "is_i".into()),
545                    (VariableName::Symbol, "this_is_a_rust_file".into()),
546                ]),
547                project_env: HashMap::default(),
548            }
549        );
550
551        assert_eq!(
552            workspace
553                .update_in(cx, |workspace, window, cx| {
554                    // Now, let's switch the active item to .ts file.
555                    workspace.activate_item(&editor1, true, true, window, cx);
556                    task_contexts(workspace, window, cx)
557                })
558                .await
559                .active_context()
560                .expect("Should have an active context"),
561            &TaskContext {
562                cwd: Some(path!("/dir").into()),
563                task_variables: TaskVariables::from_iter([
564                    (VariableName::File, path!("/dir/a.ts").into()),
565                    (VariableName::Filename, "a.ts".into()),
566                    (VariableName::RelativeFile, "a.ts".into()),
567                    (VariableName::Dirname, path!("/dir").into()),
568                    (VariableName::Stem, "a".into()),
569                    (VariableName::WorktreeRoot, path!("/dir").into()),
570                    (VariableName::Row, "1".into()),
571                    (VariableName::Column, "1".into()),
572                    (VariableName::Symbol, "this_is_a_test".into()),
573                ]),
574                project_env: HashMap::default(),
575            }
576        );
577    }
578
579    pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
580        cx.update(|cx| {
581            let state = AppState::test(cx);
582            language::init(cx);
583            crate::init(cx);
584            editor::init(cx);
585            workspace::init_settings(cx);
586            Project::init_settings(cx);
587            TaskStore::init(None);
588            state
589        })
590    }
591}