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.update(cx, |editor, _| {
304 editor.selections.newest_anchor().head().text_anchor
305 })
306 });
307
308 let mut worktree_abs_paths = workspace
309 .worktrees(cx)
310 .filter(|worktree| is_visible_directory(worktree, cx))
311 .map(|worktree| {
312 let worktree = worktree.read(cx);
313 (worktree.id(), worktree.abs_path())
314 })
315 .collect::<HashMap<_, _>>();
316
317 cx.background_spawn(async move {
318 let mut task_contexts = TaskContexts::default();
319
320 task_contexts.lsp_task_sources = lsp_task_sources;
321 task_contexts.latest_selection = latest_selection;
322
323 if let Some(editor_context_task) = editor_context_task {
324 if let Some(editor_context) = editor_context_task.await {
325 task_contexts.active_item_context =
326 Some((active_worktree, location, editor_context));
327 }
328 }
329
330 if let Some(active_worktree) = active_worktree {
331 if let Some(active_worktree_abs_path) = worktree_abs_paths.remove(&active_worktree) {
332 task_contexts.active_worktree_context =
333 Some((active_worktree, worktree_context(&active_worktree_abs_path)));
334 }
335 } else if worktree_abs_paths.len() == 1 {
336 task_contexts.active_worktree_context = worktree_abs_paths
337 .drain()
338 .next()
339 .map(|(id, abs_path)| (id, worktree_context(&abs_path)));
340 }
341
342 task_contexts.other_worktree_contexts.extend(
343 worktree_abs_paths
344 .into_iter()
345 .map(|(id, abs_path)| (id, worktree_context(&abs_path))),
346 );
347 task_contexts
348 })
349}
350
351fn is_visible_directory(worktree: &Entity<Worktree>, cx: &App) -> bool {
352 let worktree = worktree.read(cx);
353 worktree.is_visible() && worktree.root_entry().map_or(false, |entry| entry.is_dir())
354}
355
356fn worktree_context(worktree_abs_path: &Path) -> TaskContext {
357 let mut task_variables = TaskVariables::default();
358 task_variables.insert(
359 VariableName::WorktreeRoot,
360 worktree_abs_path.to_string_lossy().to_string(),
361 );
362 TaskContext {
363 cwd: Some(worktree_abs_path.to_path_buf()),
364 task_variables,
365 project_env: HashMap::default(),
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use std::{collections::HashMap, sync::Arc};
372
373 use editor::Editor;
374 use gpui::TestAppContext;
375 use language::{Language, LanguageConfig};
376 use project::{BasicContextProvider, FakeFs, Project, task_store::TaskStore};
377 use serde_json::json;
378 use task::{TaskContext, TaskVariables, VariableName};
379 use ui::VisualContext;
380 use util::{path, separator};
381 use workspace::{AppState, Workspace};
382
383 use crate::task_contexts;
384
385 #[gpui::test]
386 async fn test_default_language_context(cx: &mut TestAppContext) {
387 init_test(cx);
388 let fs = FakeFs::new(cx.executor());
389 fs.insert_tree(
390 path!("/dir"),
391 json!({
392 ".zed": {
393 "tasks.json": r#"[
394 {
395 "label": "example task",
396 "command": "echo",
397 "args": ["4"]
398 },
399 {
400 "label": "another one",
401 "command": "echo",
402 "args": ["55"]
403 },
404 ]"#,
405 },
406 "a.ts": "function this_is_a_test() { }",
407 "rust": {
408 "b.rs": "use std; fn this_is_a_rust_file() { }",
409 }
410
411 }),
412 )
413 .await;
414 let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
415 let worktree_store = project.update(cx, |project, _| project.worktree_store().clone());
416 let rust_language = Arc::new(
417 Language::new(
418 LanguageConfig::default(),
419 Some(tree_sitter_rust::LANGUAGE.into()),
420 )
421 .with_outline_query(
422 r#"(function_item
423 "fn" @context
424 name: (_) @name) @item"#,
425 )
426 .unwrap()
427 .with_context_provider(Some(Arc::new(BasicContextProvider::new(
428 worktree_store.clone(),
429 )))),
430 );
431
432 let typescript_language = Arc::new(
433 Language::new(
434 LanguageConfig::default(),
435 Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
436 )
437 .with_outline_query(
438 r#"(function_declaration
439 "async"? @context
440 "function" @context
441 name: (_) @name
442 parameters: (formal_parameters
443 "(" @context
444 ")" @context)) @item"#,
445 )
446 .unwrap()
447 .with_context_provider(Some(Arc::new(BasicContextProvider::new(
448 worktree_store.clone(),
449 )))),
450 );
451
452 let worktree_id = project.update(cx, |project, cx| {
453 project.worktrees(cx).next().unwrap().read(cx).id()
454 });
455 let (workspace, cx) =
456 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
457
458 let buffer1 = workspace
459 .update(cx, |this, cx| {
460 this.project()
461 .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
462 })
463 .await
464 .unwrap();
465 buffer1.update(cx, |this, cx| {
466 this.set_language(Some(typescript_language), cx)
467 });
468 let editor1 = cx.new_window_entity(|window, cx| {
469 Editor::for_buffer(buffer1, Some(project.clone()), window, cx)
470 });
471 let buffer2 = workspace
472 .update(cx, |this, cx| {
473 this.project().update(cx, |this, cx| {
474 this.open_buffer((worktree_id, "rust/b.rs"), cx)
475 })
476 })
477 .await
478 .unwrap();
479 buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
480 let editor2 = cx
481 .new_window_entity(|window, cx| Editor::for_buffer(buffer2, Some(project), window, cx));
482
483 let first_context = workspace
484 .update_in(cx, |workspace, window, cx| {
485 workspace.add_item_to_center(Box::new(editor1.clone()), window, cx);
486 workspace.add_item_to_center(Box::new(editor2.clone()), window, cx);
487 assert_eq!(
488 workspace.active_item(cx).unwrap().item_id(),
489 editor2.entity_id()
490 );
491 task_contexts(workspace, window, cx)
492 })
493 .await;
494
495 assert_eq!(
496 first_context
497 .active_context()
498 .expect("Should have an active context"),
499 &TaskContext {
500 cwd: Some(path!("/dir").into()),
501 task_variables: TaskVariables::from_iter([
502 (VariableName::File, path!("/dir/rust/b.rs").into()),
503 (VariableName::Filename, "b.rs".into()),
504 (VariableName::RelativeFile, separator!("rust/b.rs").into()),
505 (VariableName::Dirname, path!("/dir/rust").into()),
506 (VariableName::Stem, "b".into()),
507 (VariableName::WorktreeRoot, path!("/dir").into()),
508 (VariableName::Row, "1".into()),
509 (VariableName::Column, "1".into()),
510 ]),
511 project_env: HashMap::default(),
512 }
513 );
514
515 // And now, let's select an identifier.
516 editor2.update_in(cx, |editor, window, cx| {
517 editor.change_selections(None, window, cx, |selections| {
518 selections.select_ranges([14..18])
519 })
520 });
521
522 assert_eq!(
523 workspace
524 .update_in(cx, |workspace, window, cx| {
525 task_contexts(workspace, window, cx)
526 })
527 .await
528 .active_context()
529 .expect("Should have an active context"),
530 &TaskContext {
531 cwd: Some(path!("/dir").into()),
532 task_variables: TaskVariables::from_iter([
533 (VariableName::File, path!("/dir/rust/b.rs").into()),
534 (VariableName::Filename, "b.rs".into()),
535 (VariableName::RelativeFile, separator!("rust/b.rs").into()),
536 (VariableName::Dirname, path!("/dir/rust").into()),
537 (VariableName::Stem, "b".into()),
538 (VariableName::WorktreeRoot, path!("/dir").into()),
539 (VariableName::Row, "1".into()),
540 (VariableName::Column, "15".into()),
541 (VariableName::SelectedText, "is_i".into()),
542 (VariableName::Symbol, "this_is_a_rust_file".into()),
543 ]),
544 project_env: HashMap::default(),
545 }
546 );
547
548 assert_eq!(
549 workspace
550 .update_in(cx, |workspace, window, cx| {
551 // Now, let's switch the active item to .ts file.
552 workspace.activate_item(&editor1, true, true, window, cx);
553 task_contexts(workspace, window, cx)
554 })
555 .await
556 .active_context()
557 .expect("Should have an active context"),
558 &TaskContext {
559 cwd: Some(path!("/dir").into()),
560 task_variables: TaskVariables::from_iter([
561 (VariableName::File, path!("/dir/a.ts").into()),
562 (VariableName::Filename, "a.ts".into()),
563 (VariableName::RelativeFile, "a.ts".into()),
564 (VariableName::Dirname, path!("/dir").into()),
565 (VariableName::Stem, "a".into()),
566 (VariableName::WorktreeRoot, path!("/dir").into()),
567 (VariableName::Row, "1".into()),
568 (VariableName::Column, "1".into()),
569 (VariableName::Symbol, "this_is_a_test".into()),
570 ]),
571 project_env: HashMap::default(),
572 }
573 );
574 }
575
576 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
577 cx.update(|cx| {
578 let state = AppState::test(cx);
579 language::init(cx);
580 crate::init(cx);
581 editor::init(cx);
582 workspace::init_settings(cx);
583 Project::init_settings(cx);
584 TaskStore::init(None);
585 state
586 })
587 }
588}