oneshot_source.rs

 1//! A source of tasks, based on ad-hoc user command prompt input.
 2
 3use std::sync::Arc;
 4
 5use crate::{
 6    static_source::RevealStrategy, SpawnInTerminal, Task, TaskContext, TaskId, TaskSource,
 7};
 8use gpui::{AppContext, Context, Model};
 9
10/// A storage and source of tasks generated out of user command prompt inputs.
11pub struct OneshotSource {
12    tasks: Vec<Arc<dyn Task>>,
13}
14
15#[derive(Clone)]
16struct OneshotTask {
17    id: TaskId,
18}
19
20impl OneshotTask {
21    fn new(prompt: String) -> Self {
22        Self { id: TaskId(prompt) }
23    }
24}
25
26impl Task for OneshotTask {
27    fn id(&self) -> &TaskId {
28        &self.id
29    }
30
31    fn name(&self) -> &str {
32        &self.id.0
33    }
34
35    fn cwd(&self) -> Option<&str> {
36        None
37    }
38
39    fn exec(&self, cx: TaskContext) -> Option<SpawnInTerminal> {
40        if self.id().0.is_empty() {
41            return None;
42        }
43        let TaskContext { cwd, env } = cx;
44        Some(SpawnInTerminal {
45            id: self.id().clone(),
46            label: self.name().to_owned(),
47            command: self.id().0.clone(),
48            args: vec![],
49            cwd,
50            env,
51            use_new_terminal: Default::default(),
52            allow_concurrent_runs: Default::default(),
53            reveal: RevealStrategy::default(),
54        })
55    }
56}
57
58impl OneshotSource {
59    /// Initializes the oneshot source, preparing to store user prompts.
60    pub fn new(cx: &mut AppContext) -> Model<Box<dyn TaskSource>> {
61        cx.new_model(|_| Box::new(Self { tasks: Vec::new() }) as Box<dyn TaskSource>)
62    }
63
64    /// Spawns a certain task based on the user prompt.
65    pub fn spawn(&mut self, prompt: String) -> Arc<dyn Task> {
66        let ret = Arc::new(OneshotTask::new(prompt));
67        self.tasks.push(ret.clone());
68        ret
69    }
70}
71
72impl TaskSource for OneshotSource {
73    fn as_any(&mut self) -> &mut dyn std::any::Any {
74        self
75    }
76
77    fn tasks_for_path(
78        &mut self,
79        _path: Option<&std::path::Path>,
80        _cx: &mut gpui::ModelContext<Box<dyn TaskSource>>,
81    ) -> Vec<Arc<dyn Task>> {
82        self.tasks.clone()
83    }
84}