1use ::settings::Settings;
2use editor::{tasks::task_context, Editor};
3use gpui::{AppContext, Task as AsyncTask, ViewContext, WindowContext};
4use modal::TasksModal;
5use project::{Location, WorktreeId};
6use workspace::tasks::schedule_task;
7use workspace::{tasks::schedule_resolved_task, Workspace};
8
9mod modal;
10mod settings;
11
12pub use modal::{Rerun, Spawn};
13
14pub fn init(cx: &mut AppContext) {
15 settings::TaskSettings::register(cx);
16 cx.observe_new_views(
17 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
18 workspace
19 .register_action(spawn_task_or_modal)
20 .register_action(move |workspace, action: &modal::Rerun, 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
29 .read(cx)
30 .last_scheduled_task(action.task_id.as_ref())
31 })
32 {
33 if action.reevaluate_context {
34 let mut original_task = last_scheduled_task.original_task().clone();
35 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
36 original_task.allow_concurrent_runs = allow_concurrent_runs;
37 }
38 if let Some(use_new_terminal) = action.use_new_terminal {
39 original_task.use_new_terminal = use_new_terminal;
40 }
41 let context_task = task_context(workspace, cx);
42 cx.spawn(|workspace, mut cx| async move {
43 let task_context = context_task.await;
44 workspace
45 .update(&mut cx, |workspace, cx| {
46 schedule_task(
47 workspace,
48 task_source_kind,
49 &original_task,
50 &task_context,
51 false,
52 cx,
53 )
54 })
55 .ok()
56 })
57 .detach()
58 } else {
59 if let Some(resolved) = last_scheduled_task.resolved.as_mut() {
60 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
61 resolved.allow_concurrent_runs = allow_concurrent_runs;
62 }
63 if let Some(use_new_terminal) = action.use_new_terminal {
64 resolved.use_new_terminal = use_new_terminal;
65 }
66 }
67
68 schedule_resolved_task(
69 workspace,
70 task_source_kind,
71 last_scheduled_task,
72 false,
73 cx,
74 );
75 }
76 } else {
77 toggle_modal(workspace, cx).detach();
78 };
79 });
80 },
81 )
82 .detach();
83}
84
85fn spawn_task_or_modal(workspace: &mut Workspace, action: &Spawn, cx: &mut ViewContext<Workspace>) {
86 match &action.task_name {
87 Some(name) => spawn_task_with_name(name.clone(), cx).detach_and_log_err(cx),
88 None => toggle_modal(workspace, cx).detach(),
89 }
90}
91
92fn toggle_modal(workspace: &mut Workspace, cx: &mut ViewContext<'_, Workspace>) -> AsyncTask<()> {
93 let task_store = workspace.project().read(cx).task_store().clone();
94 let workspace_handle = workspace.weak_handle();
95 let can_open_modal = workspace.project().update(cx, |project, cx| {
96 project.is_local() || project.ssh_connection_string(cx).is_some() || project.is_via_ssh()
97 });
98 if can_open_modal {
99 let context_task = task_context(workspace, cx);
100 cx.spawn(|workspace, mut cx| async move {
101 let task_context = context_task.await;
102 workspace
103 .update(&mut cx, |workspace, cx| {
104 workspace.toggle_modal(cx, |cx| {
105 TasksModal::new(task_store.clone(), task_context, workspace_handle, cx)
106 })
107 })
108 .ok();
109 })
110 } else {
111 AsyncTask::ready(())
112 }
113}
114
115fn spawn_task_with_name(
116 name: String,
117 cx: &mut ViewContext<Workspace>,
118) -> AsyncTask<anyhow::Result<()>> {
119 cx.spawn(|workspace, mut cx| async move {
120 let context_task =
121 workspace.update(&mut cx, |workspace, cx| task_context(workspace, cx))?;
122 let task_context = context_task.await;
123 let tasks = workspace.update(&mut cx, |workspace, cx| {
124 let Some(task_inventory) = workspace
125 .project()
126 .read(cx)
127 .task_store()
128 .read(cx)
129 .task_inventory()
130 .cloned()
131 else {
132 return Vec::new();
133 };
134 let (worktree, location) = active_item_selection_properties(workspace, cx);
135 let (file, language) = location
136 .map(|location| {
137 let buffer = location.buffer.read(cx);
138 (
139 buffer.file().cloned(),
140 buffer.language_at(location.range.start),
141 )
142 })
143 .unwrap_or_default();
144 task_inventory
145 .read(cx)
146 .list_tasks(file, language, worktree, cx)
147 })?;
148
149 let did_spawn = workspace
150 .update(&mut cx, |workspace, cx| {
151 let (task_source_kind, target_task) =
152 tasks.into_iter().find(|(_, task)| task.label == name)?;
153 schedule_task(
154 workspace,
155 task_source_kind,
156 &target_task,
157 &task_context,
158 false,
159 cx,
160 );
161 Some(())
162 })?
163 .is_some();
164 if !did_spawn {
165 workspace
166 .update(&mut cx, |workspace, cx| {
167 spawn_task_or_modal(workspace, &Spawn::default(), cx);
168 })
169 .ok();
170 }
171
172 Ok(())
173 })
174}
175
176fn active_item_selection_properties(
177 workspace: &Workspace,
178 cx: &mut WindowContext,
179) -> (Option<WorktreeId>, Option<Location>) {
180 let active_item = workspace.active_item(cx);
181 let worktree_id = active_item
182 .as_ref()
183 .and_then(|item| item.project_path(cx))
184 .map(|path| path.worktree_id);
185 let location = active_item
186 .and_then(|active_item| active_item.act_as::<Editor>(cx))
187 .and_then(|editor| {
188 editor.update(cx, |editor, cx| {
189 let selection = editor.selections.newest_anchor();
190 let multi_buffer = editor.buffer().clone();
191 let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
192 let (buffer_snapshot, buffer_offset) =
193 multi_buffer_snapshot.point_to_buffer_offset(selection.head())?;
194 let buffer_anchor = buffer_snapshot.anchor_before(buffer_offset);
195 let buffer = multi_buffer.read(cx).buffer(buffer_snapshot.remote_id())?;
196 Some(Location {
197 buffer,
198 range: buffer_anchor..buffer_anchor,
199 })
200 })
201 });
202 (worktree_id, location)
203}
204
205#[cfg(test)]
206mod tests {
207 use std::{collections::HashMap, sync::Arc};
208
209 use editor::Editor;
210 use gpui::{Entity, TestAppContext};
211 use language::{Language, LanguageConfig};
212 use project::{task_store::TaskStore, BasicContextProvider, FakeFs, Project};
213 use serde_json::json;
214 use task::{TaskContext, TaskVariables, VariableName};
215 use ui::VisualContext;
216 use workspace::{AppState, Workspace};
217
218 use crate::task_context;
219
220 #[gpui::test]
221 async fn test_default_language_context(cx: &mut TestAppContext) {
222 init_test(cx);
223 let fs = FakeFs::new(cx.executor());
224 fs.insert_tree(
225 "/dir",
226 json!({
227 ".zed": {
228 "tasks.json": r#"[
229 {
230 "label": "example task",
231 "command": "echo",
232 "args": ["4"]
233 },
234 {
235 "label": "another one",
236 "command": "echo",
237 "args": ["55"]
238 },
239 ]"#,
240 },
241 "a.ts": "function this_is_a_test() { }",
242 "rust": {
243 "b.rs": "use std; fn this_is_a_rust_file() { }",
244 }
245
246 }),
247 )
248 .await;
249 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
250 let worktree_store = project.update(cx, |project, _| project.worktree_store().clone());
251 let rust_language = Arc::new(
252 Language::new(
253 LanguageConfig::default(),
254 Some(tree_sitter_rust::LANGUAGE.into()),
255 )
256 .with_outline_query(
257 r#"(function_item
258 "fn" @context
259 name: (_) @name) @item"#,
260 )
261 .unwrap()
262 .with_context_provider(Some(Arc::new(BasicContextProvider::new(
263 worktree_store.clone(),
264 )))),
265 );
266
267 let typescript_language = Arc::new(
268 Language::new(
269 LanguageConfig::default(),
270 Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
271 )
272 .with_outline_query(
273 r#"(function_declaration
274 "async"? @context
275 "function" @context
276 name: (_) @name
277 parameters: (formal_parameters
278 "(" @context
279 ")" @context)) @item"#,
280 )
281 .unwrap()
282 .with_context_provider(Some(Arc::new(BasicContextProvider::new(
283 worktree_store.clone(),
284 )))),
285 );
286
287 let worktree_id = project.update(cx, |project, cx| {
288 project.worktrees(cx).next().unwrap().read(cx).id()
289 });
290 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
291
292 let buffer1 = workspace
293 .update(cx, |this, cx| {
294 this.project()
295 .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
296 })
297 .await
298 .unwrap();
299 buffer1.update(cx, |this, cx| {
300 this.set_language(Some(typescript_language), cx)
301 });
302 let editor1 = cx.new_view(|cx| Editor::for_buffer(buffer1, Some(project.clone()), cx));
303 let buffer2 = workspace
304 .update(cx, |this, cx| {
305 this.project().update(cx, |this, cx| {
306 this.open_buffer((worktree_id, "rust/b.rs"), cx)
307 })
308 })
309 .await
310 .unwrap();
311 buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
312 let editor2 = cx.new_view(|cx| Editor::for_buffer(buffer2, Some(project), cx));
313
314 let first_context = workspace
315 .update(cx, |workspace, cx| {
316 workspace.add_item_to_center(Box::new(editor1.clone()), cx);
317 workspace.add_item_to_center(Box::new(editor2.clone()), cx);
318 assert_eq!(
319 workspace.active_item(cx).unwrap().item_id(),
320 editor2.entity_id()
321 );
322 task_context(workspace, cx)
323 })
324 .await;
325 assert_eq!(
326 first_context,
327 TaskContext {
328 cwd: Some("/dir".into()),
329 task_variables: TaskVariables::from_iter([
330 (VariableName::File, "/dir/rust/b.rs".into()),
331 (VariableName::Filename, "b.rs".into()),
332 (VariableName::RelativeFile, "rust/b.rs".into()),
333 (VariableName::Dirname, "/dir/rust".into()),
334 (VariableName::Stem, "b".into()),
335 (VariableName::WorktreeRoot, "/dir".into()),
336 (VariableName::Row, "1".into()),
337 (VariableName::Column, "1".into()),
338 ]),
339 project_env: HashMap::default(),
340 }
341 );
342
343 // And now, let's select an identifier.
344 editor2.update(cx, |editor, cx| {
345 editor.change_selections(None, cx, |selections| selections.select_ranges([14..18]))
346 });
347
348 assert_eq!(
349 workspace
350 .update(cx, |workspace, cx| { task_context(workspace, cx) })
351 .await,
352 TaskContext {
353 cwd: Some("/dir".into()),
354 task_variables: TaskVariables::from_iter([
355 (VariableName::File, "/dir/rust/b.rs".into()),
356 (VariableName::Filename, "b.rs".into()),
357 (VariableName::RelativeFile, "rust/b.rs".into()),
358 (VariableName::Dirname, "/dir/rust".into()),
359 (VariableName::Stem, "b".into()),
360 (VariableName::WorktreeRoot, "/dir".into()),
361 (VariableName::Row, "1".into()),
362 (VariableName::Column, "15".into()),
363 (VariableName::SelectedText, "is_i".into()),
364 (VariableName::Symbol, "this_is_a_rust_file".into()),
365 ]),
366 project_env: HashMap::default(),
367 }
368 );
369
370 assert_eq!(
371 workspace
372 .update(cx, |workspace, cx| {
373 // Now, let's switch the active item to .ts file.
374 workspace.activate_item(&editor1, true, true, cx);
375 task_context(workspace, cx)
376 })
377 .await,
378 TaskContext {
379 cwd: Some("/dir".into()),
380 task_variables: TaskVariables::from_iter([
381 (VariableName::File, "/dir/a.ts".into()),
382 (VariableName::Filename, "a.ts".into()),
383 (VariableName::RelativeFile, "a.ts".into()),
384 (VariableName::Dirname, "/dir".into()),
385 (VariableName::Stem, "a".into()),
386 (VariableName::WorktreeRoot, "/dir".into()),
387 (VariableName::Row, "1".into()),
388 (VariableName::Column, "1".into()),
389 (VariableName::Symbol, "this_is_a_test".into()),
390 ]),
391 project_env: HashMap::default(),
392 }
393 );
394 }
395
396 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
397 cx.update(|cx| {
398 let state = AppState::test(cx);
399 file_icons::init((), cx);
400 language::init(cx);
401 crate::init(cx);
402 editor::init(cx);
403 workspace::init_settings(cx);
404 Project::init_settings(cx);
405 TaskStore::init(None);
406 state
407 })
408 }
409}