1use std::path::PathBuf;
2
3use gpui::{AppContext, ViewContext, WindowContext};
4use modal::TasksModal;
5pub use oneshot_source::OneshotSource;
6use task::Task;
7use util::ResultExt;
8use workspace::Workspace;
9
10mod modal;
11mod oneshot_source;
12
13pub fn init(cx: &mut AppContext) {
14 cx.observe_new_views(
15 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
16 workspace
17 .register_action(|workspace, _: &modal::Spawn, cx| {
18 let inventory = workspace.project().read(cx).task_inventory().clone();
19 let workspace_handle = workspace.weak_handle();
20 workspace
21 .toggle_modal(cx, |cx| TasksModal::new(inventory, workspace_handle, cx))
22 })
23 .register_action(move |workspace, _: &modal::Rerun, cx| {
24 if let Some(task) = workspace.project().update(cx, |project, cx| {
25 project
26 .task_inventory()
27 .update(cx, |inventory, cx| inventory.last_scheduled_task(cx))
28 }) {
29 schedule_task(workspace, task.as_ref(), cx)
30 };
31 });
32 },
33 )
34 .detach();
35}
36
37fn schedule_task(workspace: &Workspace, task: &dyn Task, cx: &mut ViewContext<'_, Workspace>) {
38 let cwd = match task.cwd() {
39 Some(cwd) => Some(cwd.to_path_buf()),
40 None => task_cwd(workspace, cx).log_err().flatten(),
41 };
42 let spawn_in_terminal = task.exec(cwd);
43 if let Some(spawn_in_terminal) = spawn_in_terminal {
44 workspace.project().update(cx, |project, cx| {
45 project.task_inventory().update(cx, |inventory, _| {
46 inventory.last_scheduled_task = Some(task.id().clone());
47 })
48 });
49 cx.emit(workspace::Event::SpawnTask(spawn_in_terminal));
50 }
51}
52
53fn task_cwd(workspace: &Workspace, cx: &mut WindowContext) -> anyhow::Result<Option<PathBuf>> {
54 let project = workspace.project().read(cx);
55 let available_worktrees = project
56 .worktrees()
57 .filter(|worktree| {
58 let worktree = worktree.read(cx);
59 worktree.is_visible()
60 && worktree.is_local()
61 && worktree.root_entry().map_or(false, |e| e.is_dir())
62 })
63 .collect::<Vec<_>>();
64 let cwd = match available_worktrees.len() {
65 0 => None,
66 1 => Some(available_worktrees[0].read(cx).abs_path()),
67 _ => {
68 let cwd_for_active_entry = project.active_entry().and_then(|entry_id| {
69 available_worktrees.into_iter().find_map(|worktree| {
70 let worktree = worktree.read(cx);
71 if worktree.contains_entry(entry_id) {
72 Some(worktree.abs_path())
73 } else {
74 None
75 }
76 })
77 });
78 anyhow::ensure!(
79 cwd_for_active_entry.is_some(),
80 "Cannot determine task cwd for multiple worktrees"
81 );
82 cwd_for_active_entry
83 }
84 };
85 Ok(cwd.map(|path| path.to_path_buf()))
86}