Debian Codegraph @

helix-term/src/job.rs

raw symbols SCIP
1 use helix_event::status::StatusMessage;
2 use helix_event::{runtime_local, send_blocking};
3 use helix_view::Editor;
4 use once_cell::sync::OnceCell;
5
6 use crate::compositor::Compositor;
7
8 use futures_util::future::{BoxFuture, Future, FutureExt};
9 use futures_util::stream::{FuturesUnordered, StreamExt};
10 use tokio::sync::mpsc::{channel, Receiver, Sender};
11
12 pub type EditorCompositorCallback = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>;
13 pub type EditorCallback = Box<dyn FnOnce(&mut Editor) + Send>;
14 pub type EditorCallbackFollowup = Box<dyn FnOnce(&mut Editor) -> Option<Job> + Send>;
15
16 runtime_local! {
17 static JOB_QUEUE: OnceCell<Sender<Callback>> = OnceCell::new();
18 }
19
20 pub async fn dispatch_callback(job: Callback) {
21 let _ = JOB_QUEUE.wait().send(job).await;
22 }
23
24 pub async fn dispatch(job: impl FnOnce(&mut Editor, &mut Compositor) + Send + 'static) {
25 let _ = JOB_QUEUE
26 .wait()
27 .send(Callback::EditorCompositor(Box::new(job)))
28 .await;
29 }
30
31 pub fn dispatch_blocking(job: impl FnOnce(&mut Editor, &mut Compositor) + Send + 'static) {
32 let jobs = JOB_QUEUE.wait();
33 send_blocking(jobs, Callback::EditorCompositor(Box::new(job)))
34 }
35
36 pub enum Callback {
37 EditorCompositor(EditorCompositorCallback),
38 Editor(EditorCallback),
39 Followup(EditorCallbackFollowup),
40 }
41
42 pub type JobFuture = BoxFuture<'static, anyhow::Result<Option<Callback>>>;
43
44 pub struct Job {
45 pub future: BoxFuture<'static, anyhow::Result<Option<Callback>>>,
46 /// Do we need to wait for this job to finish before exiting?
47 pub wait: bool,
48 }
49
50 pub struct Jobs {
51 /// jobs that need to complete before we exit.
52 pub wait_futures: FuturesUnordered<JobFuture>,
53 pub callbacks: Receiver<Callback>,
54 pub status_messages: Receiver<StatusMessage>,
55 }
56
57 impl Job {
58 pub fn new<F: Future<Output = anyhow::Result<()>> + Send + 'static>(f: F) -> Self {
59 Self {
60 future: f.map(|r| r.map(|()| None)).boxed(),
61 wait: false,
62 }
63 }
64
65 pub fn with_callback<F: Future<Output = anyhow::Result<Callback>> + Send + 'static>(
66 f: F,
67 ) -> Self {
68 Self {
69 future: f.map(|r| r.map(Some)).boxed(),
70 wait: false,
71 }
72 }
73
74 pub fn wait_before_exiting(mut self) -> Self {
75 self.wait = true;
76 self
77 }
78 }
79
80 impl Jobs {
81 #[allow(clippy::new_without_default)]
82 pub fn new() -> Self {
83 let (tx, rx) = channel(1024);
84 let _ = JOB_QUEUE.set(tx);
85 let status_messages = helix_event::status::setup();
86 Self {
87 wait_futures: FuturesUnordered::new(),
88 callbacks: rx,
89 status_messages,
90 }
91 }
92
93 pub fn spawn<F: Future<Output = anyhow::Result<()>> + Send + 'static>(&mut self, f: F) {
94 self.add(Job::new(f));
95 }
96
97 pub fn callback<F: Future<Output = anyhow::Result<Callback>> + Send + 'static>(
98 &mut self,
99 f: F,
100 ) {
101 self.add(Job::with_callback(f));
102 }
103
104 pub fn handle_callback(
105 &self,
106 editor: &mut Editor,
107 compositor: &mut Compositor,
108 call: anyhow::Result<Option<Callback>>,
109 ) -> Option<Job> {
110 match call {
111 Ok(None) => None,
112 Ok(Some(call)) => match call {
113 Callback::EditorCompositor(call) => {
114 call(editor, compositor);
115 None
116 }
117 Callback::Editor(call) => {
118 call(editor);
119 None
120 }
121 Callback::Followup(call) => call(editor),
122 },
123 Err(e) => {
124 editor.set_error(format!("Async job failed: {}", e));
125 None
126 }
127 }
128 }
129
130 pub fn add(&self, j: Job) {
131 if j.wait {
132 self.wait_futures.push(j.future);
133 } else {
134 tokio::spawn(async move {
135 match j.future.await {
136 Ok(Some(cb)) => dispatch_callback(cb).await,
137 Ok(None) => (),
138 Err(err) => helix_event::status::report(err).await,
139 }
140 });
141 }
142 }
143
144 /// Blocks until all the jobs that need to be waited on are done.
145 pub async fn finish(
146 &mut self,
147 editor: &mut Editor,
148 mut compositor: Option<&mut Compositor>,
149 ) -> anyhow::Result<()> {
150 log::debug!("waiting on jobs...");
151 let mut wait_futures = std::mem::take(&mut self.wait_futures);
152
153 while let (Some(job), tail) = wait_futures.into_future().await {
154 match job {
155 Ok(callback) => {
156 wait_futures = tail;
157
158 if let Some(callback) = callback {
159 // clippy doesn't realize this is an error without the derefs
160 #[allow(clippy::needless_option_as_deref)]
161 if let Some(job) = match callback {
162 Callback::EditorCompositor(call) if compositor.is_some() => {
163 call(editor, compositor.as_deref_mut().unwrap());
164 None
165 }
166 Callback::Editor(call) => {
167 call(editor);
168 None
169 }
170 Callback::Followup(call) => call(editor),
171
172 // skip callbacks for which we don't have the necessary references
173 _ => None,
174 } {
175 if job.wait {
176 wait_futures.push(job.future);
177 }
178 }
179 }
180 }
181 Err(e) => {
182 self.wait_futures = tail;
183 return Err(e);
184 }
185 }
186 }
187
188 Ok(())
189 }
190 }