@@ -9,14 +9,15 @@ use std::{
use collections::{HashMap, VecDeque};
use gpui::{AppContext, Context, Model, ModelContext, Subscription};
use itertools::Itertools;
-use task::{Task, TaskContext, TaskId, TaskSource};
+use language::Language;
+use task::{static_source::tasks_for, Task, TaskContext, TaskSource};
use util::{post_inc, NumericPrefixWithSuffix};
use worktree::WorktreeId;
/// Inventory tracks available tasks for a given project.
pub struct Inventory {
sources: Vec<SourceInInventory>,
- last_scheduled_tasks: VecDeque<(TaskId, TaskContext)>,
+ last_scheduled_tasks: VecDeque<(Arc<dyn Task>, TaskContext)>,
}
struct SourceInInventory {
@@ -33,17 +34,17 @@ pub enum TaskSourceKind {
UserInput,
/// ~/.config/zed/task.json - like global files with task definitions, applicable to any path
AbsPath(PathBuf),
- /// Worktree-specific task definitions, e.g. dynamic tasks from open worktree file, or tasks from the worktree's .zed/task.json
+ /// Tasks from the worktree's .zed/task.json
Worktree { id: WorktreeId, abs_path: PathBuf },
- /// Buffer-specific task definitions, originating in e.g. language extension.
- Buffer,
+ /// Languages-specific tasks coming from extensions.
+ Language { name: Arc<str> },
}
impl TaskSourceKind {
fn abs_path(&self) -> Option<&Path> {
match self {
Self::AbsPath(abs_path) | Self::Worktree { abs_path, .. } => Some(abs_path),
- Self::UserInput | Self::Buffer => None,
+ Self::UserInput | Self::Language { .. } => None,
}
}
@@ -125,21 +126,38 @@ impl Inventory {
)
}
- /// Pulls its sources to list runanbles for the path given (up to the source to decide what to return for no path).
+ /// Pulls its sources to list runnables for the editor given, or all runnables for no editor.
pub fn list_tasks(
&self,
- path: Option<&Path>,
+ language: Option<Arc<Language>>,
worktree: Option<WorktreeId>,
lru: bool,
cx: &mut AppContext,
) -> Vec<(TaskSourceKind, Arc<dyn Task>)> {
+ let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
+ name: language.name(),
+ });
+ let language_tasks = language
+ .and_then(|language| {
+ let tasks = language.context_provider()?.associated_tasks()?;
+ Some((tasks, language))
+ })
+ .map(|(tasks, language)| {
+ let language_name = language.name();
+ let id_base = format!("buffer_source_{language_name}");
+ tasks_for(tasks, &id_base)
+ })
+ .unwrap_or_default()
+ .into_iter()
+ .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
+
let mut lru_score = 0_u32;
let tasks_by_usage = if lru {
self.last_scheduled_tasks.iter().rev().fold(
HashMap::default(),
- |mut tasks, (id, context)| {
+ |mut tasks, (task, context)| {
tasks
- .entry(id)
+ .entry(task.id().clone())
.or_insert_with(|| (post_inc(&mut lru_score), Some(context)));
tasks
},
@@ -158,10 +176,11 @@ impl Inventory {
.flat_map(|source| {
source
.source
- .update(cx, |source, cx| source.tasks_for_path(path, cx))
+ .update(cx, |source, cx| source.tasks_to_schedule(cx))
.into_iter()
.map(|task| (&source.kind, task))
})
+ .chain(language_tasks)
.map(|task| {
let usages = if lru {
tasks_by_usage
@@ -206,21 +225,13 @@ impl Inventory {
}
/// Returns the last scheduled task, if any of the sources contains one with the matching id.
- pub fn last_scheduled_task(&self, cx: &mut AppContext) -> Option<(Arc<dyn Task>, TaskContext)> {
- self.last_scheduled_tasks
- .back()
- .and_then(|(id, task_context)| {
- // TODO straighten the `Path` story to understand what has to be passed here: or it will break in the future.
- self.list_tasks(None, None, false, cx)
- .into_iter()
- .find(|(_, task)| task.id() == id)
- .map(|(_, task)| (task, task_context.clone()))
- })
+ pub fn last_scheduled_task(&self) -> Option<(Arc<dyn Task>, TaskContext)> {
+ self.last_scheduled_tasks.back().cloned()
}
/// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
- pub fn task_scheduled(&mut self, id: TaskId, task_context: TaskContext) {
- self.last_scheduled_tasks.push_back((id, task_context));
+ pub fn task_scheduled(&mut self, task: Arc<dyn Task>, task_context: TaskContext) {
+ self.last_scheduled_tasks.push_back((task, task_context));
if self.last_scheduled_tasks.len() > 5_000 {
self.last_scheduled_tasks.pop_front();
}
@@ -229,7 +240,7 @@ impl Inventory {
#[cfg(any(test, feature = "test-support"))]
pub mod test_inventory {
- use std::{path::Path, sync::Arc};
+ use std::sync::Arc;
use gpui::{AppContext, Context as _, Model, ModelContext, TestAppContext};
use task::{Task, TaskContext, TaskId, TaskSource};
@@ -288,9 +299,8 @@ pub mod test_inventory {
}
impl TaskSource for StaticTestSource {
- fn tasks_for_path(
+ fn tasks_to_schedule(
&mut self,
- _path: Option<&Path>,
_cx: &mut ModelContext<Box<dyn TaskSource>>,
) -> Vec<Arc<dyn Task>> {
self.tasks
@@ -307,14 +317,13 @@ pub mod test_inventory {
pub fn list_task_names(
inventory: &Model<Inventory>,
- path: Option<&Path>,
worktree: Option<WorktreeId>,
lru: bool,
cx: &mut TestAppContext,
) -> Vec<String> {
inventory.update(cx, |inventory, cx| {
inventory
- .list_tasks(path, worktree, lru, cx)
+ .list_tasks(None, worktree, lru, cx)
.into_iter()
.map(|(_, task)| task.name().to_string())
.collect()
@@ -332,20 +341,19 @@ pub mod test_inventory {
.into_iter()
.find(|(_, task)| task.name() == task_name)
.unwrap_or_else(|| panic!("Failed to find task with name {task_name}"));
- inventory.task_scheduled(task.1.id().clone(), TaskContext::default());
+ inventory.task_scheduled(task.1, TaskContext::default());
});
}
pub fn list_tasks(
inventory: &Model<Inventory>,
- path: Option<&Path>,
worktree: Option<WorktreeId>,
lru: bool,
cx: &mut TestAppContext,
) -> Vec<(TaskSourceKind, String)> {
inventory.update(cx, |inventory, cx| {
inventory
- .list_tasks(path, worktree, lru, cx)
+ .list_tasks(None, worktree, lru, cx)
.into_iter()
.map(|(source_kind, task)| (source_kind, task.name().to_string()))
.collect()
@@ -363,12 +371,12 @@ mod tests {
#[gpui::test]
fn test_task_list_sorting(cx: &mut TestAppContext) {
let inventory = cx.update(Inventory::new);
- let initial_tasks = list_task_names(&inventory, None, None, true, cx);
+ let initial_tasks = list_task_names(&inventory, None, true, cx);
assert!(
initial_tasks.is_empty(),
"No tasks expected for empty inventory, but got {initial_tasks:?}"
);
- let initial_tasks = list_task_names(&inventory, None, None, false, cx);
+ let initial_tasks = list_task_names(&inventory, None, false, cx);
assert!(
initial_tasks.is_empty(),
"No tasks expected for empty inventory, but got {initial_tasks:?}"
@@ -405,24 +413,24 @@ mod tests {
"3_task".to_string(),
];
assert_eq!(
- list_task_names(&inventory, None, None, false, cx),
+ list_task_names(&inventory, None, false, cx),
&expected_initial_state,
"Task list without lru sorting, should be sorted alphanumerically"
);
assert_eq!(
- list_task_names(&inventory, None, None, true, cx),
+ list_task_names(&inventory, None, true, cx),
&expected_initial_state,
"Tasks with equal amount of usages should be sorted alphanumerically"
);
register_task_used(&inventory, "2_task", cx);
assert_eq!(
- list_task_names(&inventory, None, None, false, cx),
+ list_task_names(&inventory, None, false, cx),
&expected_initial_state,
"Task list without lru sorting, should be sorted alphanumerically"
);
assert_eq!(
- list_task_names(&inventory, None, None, true, cx),
+ list_task_names(&inventory, None, true, cx),
vec![
"2_task".to_string(),
"1_a_task".to_string(),
@@ -436,12 +444,12 @@ mod tests {
register_task_used(&inventory, "1_task", cx);
register_task_used(&inventory, "3_task", cx);
assert_eq!(
- list_task_names(&inventory, None, None, false, cx),
+ list_task_names(&inventory, None, false, cx),
&expected_initial_state,
"Task list without lru sorting, should be sorted alphanumerically"
);
assert_eq!(
- list_task_names(&inventory, None, None, true, cx),
+ list_task_names(&inventory, None, true, cx),
vec![
"3_task".to_string(),
"1_task".to_string(),
@@ -468,12 +476,12 @@ mod tests {
"11_hello".to_string(),
];
assert_eq!(
- list_task_names(&inventory, None, None, false, cx),
+ list_task_names(&inventory, None, false, cx),
&expected_updated_state,
"Task list without lru sorting, should be sorted alphanumerically"
);
assert_eq!(
- list_task_names(&inventory, None, None, true, cx),
+ list_task_names(&inventory, None, true, cx),
vec![
"3_task".to_string(),
"1_task".to_string(),
@@ -486,12 +494,12 @@ mod tests {
register_task_used(&inventory, "11_hello", cx);
assert_eq!(
- list_task_names(&inventory, None, None, false, cx),
+ list_task_names(&inventory, None, false, cx),
&expected_updated_state,
"Task list without lru sorting, should be sorted alphanumerically"
);
assert_eq!(
- list_task_names(&inventory, None, None, true, cx),
+ list_task_names(&inventory, None, true, cx),
vec![
"11_hello".to_string(),
"3_task".to_string(),
@@ -633,36 +641,25 @@ mod tests {
.cloned()
.collect::<Vec<_>>();
- for path in [
- None,
- Some(path_1),
- Some(path_2),
- Some(worktree_path_1),
- Some(worktree_path_2),
- ] {
- assert_eq!(
- list_tasks(&inventory_with_statics, path, None, false, cx),
- all_tasks,
- "Path {path:?} choice should not adjust static runnables"
- );
- assert_eq!(
- list_tasks(&inventory_with_statics, path, Some(worktree_1), false, cx),
- worktree_1_tasks
- .iter()
- .chain(worktree_independent_tasks.iter())
- .cloned()
- .collect::<Vec<_>>(),
- "Path {path:?} choice should not adjust static runnables for worktree_1"
- );
- assert_eq!(
- list_tasks(&inventory_with_statics, path, Some(worktree_2), false, cx),
- worktree_2_tasks
- .iter()
- .chain(worktree_independent_tasks.iter())
- .cloned()
- .collect::<Vec<_>>(),
- "Path {path:?} choice should not adjust static runnables for worktree_2"
- );
- }
+ assert_eq!(
+ list_tasks(&inventory_with_statics, None, false, cx),
+ all_tasks,
+ );
+ assert_eq!(
+ list_tasks(&inventory_with_statics, Some(worktree_1), false, cx),
+ worktree_1_tasks
+ .iter()
+ .chain(worktree_independent_tasks.iter())
+ .cloned()
+ .collect::<Vec<_>>(),
+ );
+ assert_eq!(
+ list_tasks(&inventory_with_statics, Some(worktree_2), false, cx),
+ worktree_2_tasks
+ .iter()
+ .chain(worktree_independent_tasks.iter())
+ .cloned()
+ .collect::<Vec<_>>(),
+ );
}
}
@@ -1,8 +1,8 @@
-use std::path::PathBuf;
+use std::{path::PathBuf, sync::Arc};
use editor::Editor;
-use gpui::{AppContext, ViewContext, WindowContext};
-use language::Point;
+use gpui::{AppContext, ViewContext, WeakView, WindowContext};
+use language::{Language, Point};
use modal::{Spawn, TasksModal};
use project::{Location, WorktreeId};
use task::{Task, TaskContext, TaskVariables, VariableName};
@@ -19,9 +19,7 @@ pub fn init(cx: &mut AppContext) {
.register_action(move |workspace, action: &modal::Rerun, cx| {
if let Some((task, old_context)) =
workspace.project().update(cx, |project, cx| {
- project
- .task_inventory()
- .update(cx, |inventory, cx| inventory.last_scheduled_task(cx))
+ project.task_inventory().read(cx).last_scheduled_task()
})
{
let task_context = if action.reevaluate_context {
@@ -30,7 +28,7 @@ pub fn init(cx: &mut AppContext) {
} else {
old_context
};
- schedule_task(workspace, task.as_ref(), task_context, false, cx)
+ schedule_task(workspace, &task, task_context, false, cx)
};
});
},
@@ -57,19 +55,16 @@ fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
cx.spawn(|workspace, mut cx| async move {
let did_spawn = workspace
.update(&mut cx, |this, cx| {
- let active_item = this
- .active_item(cx)
- .and_then(|item| item.project_path(cx))
- .map(|path| path.worktree_id);
+ let (worktree, language) = active_item_selection_properties(&workspace, cx);
let tasks = this.project().update(cx, |project, cx| {
project.task_inventory().update(cx, |inventory, cx| {
- inventory.list_tasks(None, active_item, false, cx)
+ inventory.list_tasks(language, worktree, false, cx)
})
});
let (_, target_task) = tasks.into_iter().find(|(_, task)| task.name() == name)?;
let cwd = task_cwd(this, cx).log_err().flatten();
let task_context = task_context(this, cwd, cx);
- schedule_task(this, target_task.as_ref(), task_context, false, cx);
+ schedule_task(this, &target_task, task_context, false, cx);
Some(())
})
.ok()
@@ -86,6 +81,33 @@ fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
.detach();
}
+fn active_item_selection_properties(
+ workspace: &WeakView<Workspace>,
+ cx: &mut WindowContext,
+) -> (Option<WorktreeId>, Option<Arc<Language>>) {
+ let active_item = workspace
+ .update(cx, |workspace, cx| workspace.active_item(cx))
+ .ok()
+ .flatten();
+ let worktree_id = active_item
+ .as_ref()
+ .and_then(|item| item.project_path(cx))
+ .map(|path| path.worktree_id);
+ let language = active_item
+ .and_then(|active_item| active_item.act_as::<Editor>(cx))
+ .and_then(|editor| {
+ editor.update(cx, |editor, cx| {
+ let selection = editor.selections.newest::<usize>(cx);
+ let (buffer, buffer_position, _) = editor
+ .buffer()
+ .read(cx)
+ .point_to_buffer_offset(selection.start, cx)?;
+ buffer.read(cx).language_at(buffer_position)
+ })
+ });
+ (worktree_id, language)
+}
+
fn task_context(
workspace: &Workspace,
cwd: Option<PathBuf>,
@@ -93,8 +115,7 @@ fn task_context(
) -> TaskContext {
let current_editor = workspace
.active_item(cx)
- .and_then(|item| item.act_as::<Editor>(cx))
- .clone();
+ .and_then(|item| item.act_as::<Editor>(cx));
if let Some(current_editor) = current_editor {
(|| {
let editor = current_editor.read(cx);
@@ -190,7 +211,7 @@ fn task_context(
fn schedule_task(
workspace: &Workspace,
- task: &dyn Task,
+ task: &Arc<dyn Task>,
task_cx: TaskContext,
omit_history: bool,
cx: &mut ViewContext<'_, Workspace>,
@@ -200,7 +221,7 @@ fn schedule_task(
if !omit_history {
workspace.project().update(cx, |project, cx| {
project.task_inventory().update(cx, |inventory, _| {
- inventory.task_scheduled(task.id().clone(), task_cx);
+ inventory.task_scheduled(Arc::clone(task), task_cx);
})
});
}
@@ -1,5 +1,6 @@
-use std::{path::PathBuf, sync::Arc};
+use std::sync::Arc;
+use crate::{active_item_selection_properties, schedule_task};
use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{
impl_actions, rems, AppContext, DismissEvent, EventEmitter, FocusableView, InteractiveElement,
@@ -10,7 +11,7 @@ use picker::{
highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
Picker, PickerDelegate,
};
-use project::{Inventory, ProjectPath, TaskSourceKind};
+use project::{Inventory, TaskSourceKind};
use task::{oneshot_source::OneshotSource, Task, TaskContext};
use ui::{
div, v_flex, ButtonCommon, ButtonSize, Clickable, Color, FluentBuilder as _, IconButton,
@@ -20,7 +21,6 @@ use ui::{
use util::{paths::PathExt, ResultExt};
use workspace::{ModalView, Workspace};
-use crate::schedule_task;
use serde::Deserialize;
/// Spawn a task with name or open tasks modal
@@ -116,20 +116,6 @@ impl TasksModalDelegate {
Some(())
});
}
- fn active_item_path(
- workspace: &WeakView<Workspace>,
- cx: &mut ViewContext<'_, Picker<Self>>,
- ) -> Option<(PathBuf, ProjectPath)> {
- let workspace = workspace.upgrade()?.read(cx);
- let project = workspace.project().read(cx);
- let active_item = workspace.active_item(cx)?;
- active_item.project_path(cx).and_then(|project_path| {
- project
- .worktree_for_id(project_path.worktree_id, cx)
- .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path))
- .zip(Some(project_path))
- })
- }
}
pub(crate) struct TasksModal {
@@ -212,15 +198,10 @@ impl PickerDelegate for TasksModalDelegate {
let Some(candidates) = picker
.update(&mut cx, |picker, cx| {
let candidates = picker.delegate.candidates.get_or_insert_with(|| {
- let (path, worktree) =
- match Self::active_item_path(&picker.delegate.workspace, cx) {
- Some((abs_path, project_path)) => {
- (Some(abs_path), Some(project_path.worktree_id))
- }
- None => (None, None),
- };
+ let (worktree, language) =
+ active_item_selection_properties(&picker.delegate.workspace, cx);
picker.delegate.inventory.update(cx, |inventory, cx| {
- inventory.list_tasks(path.as_deref(), worktree, true, cx)
+ inventory.list_tasks(language, worktree, true, cx)
})
});
@@ -283,7 +264,7 @@ impl PickerDelegate for TasksModalDelegate {
.update(cx, |workspace, cx| {
schedule_task(
workspace,
- task.as_ref(),
+ &task,
self.task_context.clone(),
omit_history_entry,
cx,
@@ -308,7 +289,7 @@ impl PickerDelegate for TasksModalDelegate {
let (source_kind, _) = &candidates.get(hit.candidate_id)?;
let details = match source_kind {
TaskSourceKind::UserInput => "user input".to_string(),
- TaskSourceKind::Buffer => "language extension".to_string(),
+ TaskSourceKind::Language { name } => format!("{name} language"),
TaskSourceKind::Worktree { abs_path, .. } | TaskSourceKind::AbsPath(abs_path) => {
abs_path.compact().to_string_lossy().to_string()
}
@@ -381,7 +362,7 @@ impl PickerDelegate for TasksModalDelegate {
.update(cx, |workspace, cx| {
schedule_task(
workspace,
- task.as_ref(),
+ &task,
self.task_context.clone(),
omit_history_entry,
cx,