1use std::sync::Arc;
2
3use ::settings::Settings;
4use editor::{tasks::task_context, Editor};
5use gpui::{AppContext, ViewContext, WindowContext};
6use language::Language;
7use modal::TasksModal;
8use project::WorktreeId;
9use workspace::tasks::schedule_task;
10use workspace::{tasks::schedule_resolved_task, Workspace};
11
12mod modal;
13mod settings;
14
15pub use modal::Spawn;
16
17pub fn init(cx: &mut AppContext) {
18 settings::TaskSettings::register(cx);
19 cx.observe_new_views(
20 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
21 workspace
22 .register_action(spawn_task_or_modal)
23 .register_action(move |workspace, action: &modal::Rerun, cx| {
24 if let Some((task_source_kind, mut last_scheduled_task)) =
25 workspace.project().update(cx, |project, cx| {
26 project.task_inventory().read(cx).last_scheduled_task()
27 })
28 {
29 if action.reevaluate_context {
30 let mut original_task = last_scheduled_task.original_task().clone();
31 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
32 original_task.allow_concurrent_runs = allow_concurrent_runs;
33 }
34 if let Some(use_new_terminal) = action.use_new_terminal {
35 original_task.use_new_terminal = use_new_terminal;
36 }
37 let task_context = task_context(workspace, cx);
38 schedule_task(
39 workspace,
40 task_source_kind,
41 &original_task,
42 &task_context,
43 false,
44 cx,
45 )
46 } else {
47 if let Some(resolved) = last_scheduled_task.resolved.as_mut() {
48 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
49 resolved.allow_concurrent_runs = allow_concurrent_runs;
50 }
51 if let Some(use_new_terminal) = action.use_new_terminal {
52 resolved.use_new_terminal = use_new_terminal;
53 }
54 }
55
56 schedule_resolved_task(
57 workspace,
58 task_source_kind,
59 last_scheduled_task,
60 false,
61 cx,
62 );
63 }
64 } else {
65 toggle_modal(workspace, cx);
66 };
67 });
68 },
69 )
70 .detach();
71}
72
73fn spawn_task_or_modal(workspace: &mut Workspace, action: &Spawn, cx: &mut ViewContext<Workspace>) {
74 match &action.task_name {
75 Some(name) => spawn_task_with_name(name.clone(), cx),
76 None => toggle_modal(workspace, cx),
77 }
78}
79
80fn toggle_modal(workspace: &mut Workspace, cx: &mut ViewContext<'_, Workspace>) {
81 let inventory = workspace.project().read(cx).task_inventory().clone();
82 let workspace_handle = workspace.weak_handle();
83 let task_context = task_context(workspace, cx);
84 workspace.toggle_modal(cx, |cx| {
85 TasksModal::new(inventory, task_context, workspace_handle, cx)
86 })
87}
88
89fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
90 cx.spawn(|workspace, mut cx| async move {
91 let did_spawn = workspace
92 .update(&mut cx, |workspace, cx| {
93 let (worktree, language) = active_item_selection_properties(workspace, cx);
94 let tasks = workspace.project().update(cx, |project, cx| {
95 project
96 .task_inventory()
97 .update(cx, |inventory, _| inventory.list_tasks(language, worktree))
98 });
99 let (task_source_kind, target_task) =
100 tasks.into_iter().find(|(_, task)| task.label == name)?;
101 let task_context = task_context(workspace, cx);
102 schedule_task(
103 workspace,
104 task_source_kind,
105 &target_task,
106 &task_context,
107 false,
108 cx,
109 );
110 Some(())
111 })
112 .ok()
113 .flatten()
114 .is_some();
115 if !did_spawn {
116 workspace
117 .update(&mut cx, |workspace, cx| {
118 spawn_task_or_modal(workspace, &Spawn::default(), cx);
119 })
120 .ok();
121 }
122 })
123 .detach();
124}
125
126fn active_item_selection_properties(
127 workspace: &Workspace,
128 cx: &mut WindowContext,
129) -> (Option<WorktreeId>, Option<Arc<Language>>) {
130 let active_item = workspace.active_item(cx);
131 let worktree_id = active_item
132 .as_ref()
133 .and_then(|item| item.project_path(cx))
134 .map(|path| path.worktree_id);
135 let language = active_item
136 .and_then(|active_item| active_item.act_as::<Editor>(cx))
137 .and_then(|editor| {
138 editor.update(cx, |editor, cx| {
139 let selection = editor.selections.newest::<usize>(cx);
140 let (buffer, buffer_position, _) = editor
141 .buffer()
142 .read(cx)
143 .point_to_buffer_offset(selection.start, cx)?;
144 buffer.read(cx).language_at(buffer_position)
145 })
146 });
147 (worktree_id, language)
148}
149
150#[cfg(test)]
151mod tests {
152 use std::sync::Arc;
153
154 use editor::Editor;
155 use gpui::{Entity, TestAppContext};
156 use language::{BasicContextProvider, Language, LanguageConfig};
157 use project::{FakeFs, Project};
158 use serde_json::json;
159 use task::{TaskContext, TaskVariables, VariableName};
160 use ui::VisualContext;
161 use workspace::{AppState, Workspace};
162
163 use crate::task_context;
164
165 #[gpui::test]
166 async fn test_default_language_context(cx: &mut TestAppContext) {
167 init_test(cx);
168 let fs = FakeFs::new(cx.executor());
169 fs.insert_tree(
170 "/dir",
171 json!({
172 ".zed": {
173 "tasks.json": r#"[
174 {
175 "label": "example task",
176 "command": "echo",
177 "args": ["4"]
178 },
179 {
180 "label": "another one",
181 "command": "echo",
182 "args": ["55"]
183 },
184 ]"#,
185 },
186 "a.ts": "function this_is_a_test() { }",
187 "rust": {
188 "b.rs": "use std; fn this_is_a_rust_file() { }",
189 }
190
191 }),
192 )
193 .await;
194
195 let rust_language = Arc::new(
196 Language::new(
197 LanguageConfig::default(),
198 Some(tree_sitter_rust::language()),
199 )
200 .with_outline_query(
201 r#"(function_item
202 "fn" @context
203 name: (_) @name) @item"#,
204 )
205 .unwrap()
206 .with_context_provider(Some(Arc::new(BasicContextProvider))),
207 );
208
209 let typescript_language = Arc::new(
210 Language::new(
211 LanguageConfig::default(),
212 Some(tree_sitter_typescript::language_typescript()),
213 )
214 .with_outline_query(
215 r#"(function_declaration
216 "async"? @context
217 "function" @context
218 name: (_) @name
219 parameters: (formal_parameters
220 "(" @context
221 ")" @context)) @item"#,
222 )
223 .unwrap()
224 .with_context_provider(Some(Arc::new(BasicContextProvider))),
225 );
226 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
227 let worktree_id = project.update(cx, |project, cx| {
228 project.worktrees().next().unwrap().read(cx).id()
229 });
230 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
231
232 let buffer1 = workspace
233 .update(cx, |this, cx| {
234 this.project()
235 .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
236 })
237 .await
238 .unwrap();
239 buffer1.update(cx, |this, cx| {
240 this.set_language(Some(typescript_language), cx)
241 });
242 let editor1 = cx.new_view(|cx| Editor::for_buffer(buffer1, Some(project.clone()), cx));
243 let buffer2 = workspace
244 .update(cx, |this, cx| {
245 this.project().update(cx, |this, cx| {
246 this.open_buffer((worktree_id, "rust/b.rs"), cx)
247 })
248 })
249 .await
250 .unwrap();
251 buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
252 let editor2 = cx.new_view(|cx| Editor::for_buffer(buffer2, Some(project), cx));
253 workspace.update(cx, |this, cx| {
254 this.add_item_to_center(Box::new(editor1.clone()), cx);
255 this.add_item_to_center(Box::new(editor2.clone()), cx);
256 assert_eq!(this.active_item(cx).unwrap().item_id(), editor2.entity_id());
257 assert_eq!(
258 task_context(this, cx),
259 TaskContext {
260 cwd: Some("/dir".into()),
261 task_variables: TaskVariables::from_iter([
262 (VariableName::File, "/dir/rust/b.rs".into()),
263 (VariableName::WorktreeRoot, "/dir".into()),
264 (VariableName::Row, "1".into()),
265 (VariableName::Column, "1".into()),
266 ])
267 }
268 );
269 // And now, let's select an identifier.
270 editor2.update(cx, |this, cx| {
271 this.change_selections(None, cx, |selections| selections.select_ranges([14..18]))
272 });
273 assert_eq!(
274 task_context(this, cx),
275 TaskContext {
276 cwd: Some("/dir".into()),
277 task_variables: TaskVariables::from_iter([
278 (VariableName::File, "/dir/rust/b.rs".into()),
279 (VariableName::WorktreeRoot, "/dir".into()),
280 (VariableName::Row, "1".into()),
281 (VariableName::Column, "15".into()),
282 (VariableName::SelectedText, "is_i".into()),
283 (VariableName::Symbol, "this_is_a_rust_file".into()),
284 ])
285 }
286 );
287
288 // Now, let's switch the active item to .ts file.
289 this.activate_item(&editor1, cx);
290 assert_eq!(
291 task_context(this, cx),
292 TaskContext {
293 cwd: Some("/dir".into()),
294 task_variables: TaskVariables::from_iter([
295 (VariableName::File, "/dir/a.ts".into()),
296 (VariableName::WorktreeRoot, "/dir".into()),
297 (VariableName::Row, "1".into()),
298 (VariableName::Column, "1".into()),
299 (VariableName::Symbol, "this_is_a_test".into()),
300 ])
301 }
302 );
303 });
304 }
305
306 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
307 cx.update(|cx| {
308 let state = AppState::test(cx);
309 file_icons::init((), cx);
310 language::init(cx);
311 crate::init(cx);
312 editor::init(cx);
313 workspace::init_settings(cx);
314 Project::init_settings(cx);
315 state
316 })
317 }
318}