on master help sign in
Add some async job infrastructure.
commitd64d75e72434842f2cceff2c77a03efab5e7a0bc authorJoe Neeman <joeneeman@gmail.com> dateMon 28 Jun 2021, 07:48 (5 years ago) parentc9be480
6 files changed+133−42
helix-term/src/application.rs+10−24 helix-term/src/commands.rs+18−14 helix-term/src/compositor.rs+2−2 helix-term/src/job.rs+100 helix-term/src/lib.rs+1 helix-term/src/ui/editor.rs+2−2
helix-term/src/application.rs+10−24
@@ -6,6 +6,7 @@ use crate::{
66 args::Args,
77 compositor::Compositor,
88 config::Config,
9+ job::Jobs,
910 keymap::Keymaps,
1011 ui::{self, Spinner},
1112};
@@ -31,13 +32,6 @@ use crossterm::{
3132
3233use futures_util::{future, stream::FuturesUnordered};
3334
34−type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
35−pub type LspCallback =
36− BoxFuture<Result<Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>, anyhow::Error>>;
37−
38−pub type LspCallbacks = FuturesUnordered<LspCallback>;
39−pub type LspCallbackWrapper = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>;
40−
4135pub struct Application {
4236 compositor: Compositor,
4337 editor: Editor,
@@ -48,7 +42,7 @@ pub struct Application {
4842 theme_loader: Arc<theme::Loader>,
4943 syn_loader: Arc<syntax::Loader>,
5044
51− callbacks: LspCallbacks,
45+ jobs: Jobs,
5246 lsp_progress: LspProgressMap,
5347}
5448
@@ -120,7 +114,7 @@ impl Application {
120114 theme_loader,
121115 syn_loader,
122116
123− callbacks: FuturesUnordered::new(),
117+ jobs: Jobs::new(),
124118 lsp_progress: LspProgressMap::new(),
125119 };
126120
@@ -130,11 +124,11 @@ impl Application {
130124 fn render(&mut self) {
131125 let editor = &mut self.editor;
132126 let compositor = &mut self.compositor;
133− let callbacks = &mut self.callbacks;
127+ let jobs = &mut self.jobs;
134128
135129 let mut cx = crate::compositor::Context {
136130 editor,
137− callbacks,
131+ jobs,
138132 scroll: None,
139133 };
140134
@@ -148,6 +142,7 @@ impl Application {
148142
149143 loop {
150144 if self.editor.should_close() {
145+ self.jobs.finish();
151146 break;
152147 }
153148
@@ -172,27 +167,18 @@ impl Application {
172167 }
173168 self.render();
174169 }
175− Some(callback) = &mut self.callbacks.next() => {
176− self.handle_language_server_callback(callback)
170+ Some(callback) = self.jobs.next() => {
171+ self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback);
172+ self.render();
177173 }
178174 }
179175 }
180176 }
181− pub fn handle_language_server_callback(
182− &mut self,
183− callback: Result<LspCallbackWrapper, anyhow::Error>,
184− ) {
185− if let Ok(callback) = callback {
186− // TODO: handle Err()
187− callback(&mut self.editor, &mut self.compositor);
188− self.render();
189− }
190− }
191177
192178 pub fn handle_terminal_events(&mut self, event: Option<Result<Event, crossterm::ErrorKind>>) {
193179 let mut cx = crate::compositor::Context {
194180 editor: &mut self.editor,
195− callbacks: &mut self.callbacks,
181+ jobs: &mut self.jobs,
196182 scroll: None,
197183 };
198184 // Handle key events
helix-term/src/commands.rs+18−14
@@ -35,8 +35,8 @@ use crate::{
3535 ui::{self, Completion, Picker, Popup, Prompt, PromptEvent},
3636};
3737
38−use crate::application::{LspCallback, LspCallbackWrapper, LspCallbacks};
39−use futures_util::FutureExt;
38+use crate::job::{self, Job, JobFuture, Jobs};
39+use futures_util::{FutureExt, TryFutureExt};
4040use std::{fmt, future::Future, path::Display, str::FromStr};
4141
4242use std::{
@@ -54,7 +54,7 @@ pub struct Context<'a> {
5454
5555 pub callback: Option<crate::compositor::Callback>,
5656 pub on_next_key_callback: Option<Box<dyn FnOnce(&mut Context, KeyEvent)>>,
57− pub callbacks: &'a mut LspCallbacks,
57+ pub jobs: &'a mut Jobs,
5858}
5959
6060impl<'a> Context<'a> {
@@ -85,13 +85,13 @@ impl<'a> Context<'a> {
8585 let callback = Box::pin(async move {
8686 let json = call.await?;
8787 let response = serde_json::from_value(json)?;
88− let call: LspCallbackWrapper =
88+ let call: job::Callback =
8989 Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
9090 callback(editor, compositor, response)
9191 });
9292 Ok(call)
9393 });
94− self.callbacks.push(callback);
94+ self.jobs.callback(callback);
9595 }
9696
9797 /// Returns 1 if no explicit count was provided
@@ -1149,7 +1149,7 @@ mod cmd {
11491149 path: Option<P>,
11501150 ) -> Result<tokio::task::JoinHandle<Result<(), anyhow::Error>>, anyhow::Error> {
11511151 use anyhow::anyhow;
1152− let callbacks = &mut cx.callbacks;
1152+ let jobs = &mut cx.jobs;
11531153 let (view, doc) = current!(cx.editor);
11541154
11551155 if let Some(path) = path {
@@ -1168,7 +1168,7 @@ mod cmd {
11681168 doc.format().map(|fmt| {
11691169 let shared = fmt.shared();
11701170 let callback = make_format_callback(doc.id(), doc.version(), true, shared.clone());
1171− callbacks.push(callback);
1171+ jobs.callback(callback);
11721172 shared
11731173 })
11741174 } else {
@@ -1178,8 +1178,12 @@ mod cmd {
11781178 }
11791179
11801180 fn write(cx: &mut compositor::Context, args: &[&str], event: PromptEvent) {
1181− if let Err(e) = write_impl(cx, args.first()) {
1182− cx.editor.set_error(e.to_string());
1181+ match write_impl(cx, args.first()) {
1182+ Err(e) => cx.editor.set_error(e.to_string()),
1183+ Ok(handle) => {
1184+ cx.jobs
1185+ .add(Job::new(handle.unwrap_or_else(|e| Err(e.into()))).wait_before_exiting());
1186+ }
11831187 };
11841188 }
11851189
@@ -1192,7 +1196,7 @@ mod cmd {
11921196
11931197 if let Some(format) = doc.format() {
11941198 let callback = make_format_callback(doc.id(), doc.version(), false, format);
1195− cx.callbacks.push(callback);
1199+ cx.jobs.callback(callback);
11961200 }
11971201 }
11981202
@@ -1918,10 +1922,10 @@ fn make_format_callback(
19181922 doc_version: i32,
19191923 set_unmodified: bool,
19201924 format: impl Future<Output = helix_lsp::util::LspFormatting> + Send + 'static,
1921−) -> LspCallback {
1922− Box::pin(async move {
1925+) -> impl Future<Output = anyhow::Result<job::Callback>> {
1926+ async move {
19231927 let format = format.await;
1924− let call: LspCallbackWrapper =
1928+ let call: job::Callback =
19251929 Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
19261930 let view_id = view!(editor).id;
19271931 if let Some(doc) = editor.document_mut(doc_id) {
@@ -1937,7 +1941,7 @@ fn make_format_callback(
19371941 }
19381942 });
19391943 Ok(call)
1940− })
1944+ }
19411945}
19421946
19431947enum Open {
helix-term/src/compositor.rs+2−2
@@ -26,12 +26,12 @@ pub enum EventResult {
2626
2727use helix_view::Editor;
2828
29−use crate::application::LspCallbacks;
29+use crate::job::Jobs;
3030
3131pub struct Context<'a> {
3232 pub editor: &'a mut Editor,
3333 pub scroll: Option<usize>,
34− pub callbacks: &'a mut LspCallbacks,
34+ pub jobs: &'a mut Jobs,
3535}
3636
3737pub trait Component: Any + AnyComponent {
helix-term/src/job.rsnew file+100
@@ -0,0 +1,100 @@
1+use helix_view::Editor;
2+
3+use crate::compositor::Compositor;
4+
5+use futures_util::future::{self, BoxFuture, Future, FutureExt};
6+use futures_util::stream::{self, FuturesUnordered, Select, StreamExt};
7+
8+pub type Callback = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>;
9+pub type JobFuture = BoxFuture<'static, anyhow::Result<Option<Callback>>>;
10+
11+pub struct Job {
12+ pub future: BoxFuture<'static, anyhow::Result<Option<Callback>>>,
13+ /// Do we need to wait for this job to finish before exiting?
14+ pub wait: bool,
15+}
16+
17+#[derive(Default)]
18+pub struct Jobs {
19+ futures: FuturesUnordered<JobFuture>,
20+ /// These are the ones that need to complete before we exit.
21+ wait_futures: FuturesUnordered<JobFuture>,
22+}
23+
24+impl Job {
25+ pub fn new<F: Future<Output = anyhow::Result<()>> + Send + 'static>(f: F) -> Job {
26+ Job {
27+ future: f.map(|r| r.map(|()| None)).boxed(),
28+ wait: false,
29+ }
30+ }
31+
32+ pub fn with_callback<F: Future<Output = anyhow::Result<Callback>> + Send + 'static>(
33+ f: F,
34+ ) -> Job {
35+ Job {
36+ future: f.map(|r| r.map(|x| Some(x))).boxed(),
37+ wait: false,
38+ }
39+ }
40+
41+ pub fn wait_before_exiting(mut self) -> Job {
42+ self.wait = true;
43+ self
44+ }
45+}
46+
47+impl Jobs {
48+ pub fn new() -> Jobs {
49+ Jobs::default()
50+ }
51+
52+ pub fn spawn<F: Future<Output = anyhow::Result<()>> + Send + 'static>(&mut self, f: F) {
53+ self.add(Job::new(f));
54+ }
55+
56+ pub fn callback<F: Future<Output = anyhow::Result<Callback>> + Send + 'static>(
57+ &mut self,
58+ f: F,
59+ ) {
60+ self.add(Job::with_callback(f));
61+ }
62+
63+ pub fn handle_callback(
64+ &mut self,
65+ editor: &mut Editor,
66+ compositor: &mut Compositor,
67+ call: anyhow::Result<Option<Callback>>,
68+ ) {
69+ match call {
70+ Ok(None) => {}
71+ Ok(Some(call)) => {
72+ call(editor, compositor);
73+ }
74+ Err(e) => {
75+ editor.set_error(format!("Async job failed: {}", e));
76+ }
77+ }
78+ }
79+
80+ pub fn next<'a>(
81+ &'a mut self,
82+ ) -> impl Future<Output = Option<anyhow::Result<Option<Callback>>>> + 'a {
83+ future::select(self.futures.next(), self.wait_futures.next())
84+ .map(|either| either.factor_first().0)
85+ }
86+
87+ pub fn add(&mut self, j: Job) {
88+ if j.wait {
89+ self.wait_futures.push(j.future);
90+ } else {
91+ self.futures.push(j.future);
92+ }
93+ }
94+
95+ /// Blocks until all the jobs that need to be waited on are done.
96+ pub fn finish(&mut self) {
97+ let wait_futures = std::mem::take(&mut self.wait_futures);
98+ helix_lsp::block_on(wait_futures.for_each(|_| future::ready(())));
99+ }
100+}
helix-term/src/lib.rs+1
@@ -8,5 +8,6 @@ pub mod args;
88pub mod commands;
99pub mod compositor;
1010pub mod config;
11+pub mod job;
1112pub mod keymap;
1213pub mod ui;
helix-term/src/ui/editor.rs+2−2
@@ -621,7 +621,7 @@ impl Component for EditorView {
621621 count: None,
622622 callback: None,
623623 on_next_key_callback: None,
624− callbacks: cx.callbacks,
624+ jobs: cx.jobs,
625625 };
626626
627627 if let Some(on_next_key) = self.on_next_key.take() {
@@ -639,7 +639,7 @@ impl Component for EditorView {
639639 // use a fake context here
640640 let mut cx = Context {
641641 editor: cxt.editor,
642− callbacks: cxt.callbacks,
642+ jobs: cxt.jobs,
643643 scroll: None,
644644 };
645645 let res = completion.handle_event(event, &mut cx);