Skip to main content

aylis_core/
tasks.rs

1//! Trabalho em segundo plano ligado a um dono (um componente ou um form): quando o dono é
2//! liberado (o form fechou), o resultado é descartado, em vez de rodar sobre um form que não
3//! existe mais (o acesso à memória de um form já fechado).
4//!
5//! - [`Poster::post_to`]: de outra thread, roda na thread da tela, se o dono ainda existe;
6//! - [`Ui::background`]: o trabalho numa thread e o fim na tela (o jeito documentado; na web,
7//!   onde o wasm não cria threads, roda na própria thread da tela);
8//! - [`Ui::spawn_local`]: uma tarefa `async` na thread da tela, cancelada com o dono (para
9//!   esperar rede e arquivos sem travar, e para bibliotecas `async`). É para **esperar**, não
10//!   para calcular: um cálculo pesado numa tarefa `async` trava a tela.
11
12use std::collections::HashMap;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::{Arc, Mutex};
16use std::task::{Context, Poll, Wake, Waker};
17
18use crate::component::ComponentId;
19use crate::post::Poster;
20use crate::ui::Ui;
21
22impl Poster {
23    /// Como [`post`](Self::post), ligado a `owner`: se ele foi liberado até lá, `job` é
24    /// descartado.
25    pub fn post_to(&self, owner: ComponentId, job: impl FnOnce(&mut Ui) + Send + 'static) {
26        self.post(move |ui| {
27            if ui.contains(owner) {
28                job(ui);
29            }
30        });
31    }
32}
33
34/// O fim de uma tarefa: a função que roda na tela com o resultado.
35type Finish = Box<dyn FnOnce(&mut Ui)>;
36
37pub(crate) struct LocalTask {
38    owner: ComponentId,
39    future: Pin<Box<dyn Future<Output = Finish>>>,
40}
41
42#[derive(Default)]
43pub(crate) struct Tasks {
44    next: u64,
45    running: HashMap<u64, LocalTask>,
46}
47
48/// Acorda uma tarefa: pede à tela (de qualquer thread) para avançá-la.
49struct TaskWaker {
50    id: u64,
51    poster: Poster,
52}
53
54impl Wake for TaskWaker {
55    fn wake(self: Arc<Self>) {
56        let id = self.id;
57        self.poster.post(move |ui| ui.poll_task(id));
58    }
59}
60
61impl Ui {
62    /// Roda `work` numa thread e, no fim, `done` na tela com o resultado, se `owner` ainda
63    /// existe (sem acessar o form
64    /// fechado). Na web, onde o wasm não cria threads, `work` roda na thread da tela: funciona,
65    /// mas a tela espera durante um cálculo pesado (uma espera de rede vai pelo
66    /// [`spawn_local`](Self::spawn_local)).
67    pub fn background<T: Send + 'static>(
68        &mut self,
69        owner: ComponentId,
70        work: impl FnOnce() -> T + Send + 'static,
71        done: impl FnOnce(&mut Ui, T) + Send + 'static,
72    ) {
73        let poster = self.poster();
74        #[cfg(not(target_arch = "wasm32"))]
75        std::thread::spawn(move || {
76            let value = work();
77            poster.post_to(owner, move |ui| done(ui, value));
78        });
79        #[cfg(target_arch = "wasm32")]
80        {
81            let value = work();
82            poster.post_to(owner, move |ui| done(ui, value));
83        }
84    }
85
86    /// Uma tarefa `async` na thread da tela, ligada a `owner`: com o dono liberado, ela é
87    /// cancelada (o `future` é descartado e `done` não roda). No fim, `done` recebe o
88    /// resultado na tela.
89    pub fn spawn_local<T: 'static>(&mut self, owner: ComponentId, future: impl Future<Output = T> + 'static, done: impl FnOnce(&mut Ui, T) + 'static) {
90        let future: Pin<Box<dyn Future<Output = Finish>>> = Box::pin(async move {
91            let value = future.await;
92            Box::new(move |ui: &mut Ui| done(ui, value)) as Finish
93        });
94        let id = self.tasks.next;
95        self.tasks.next += 1;
96        self.tasks.running.insert(id, LocalTask { owner, future });
97        self.poll_task(id);
98    }
99
100    /// Avança a tarefa `id` (a primeira vez e a cada vez que ela é acordada).
101    pub(crate) fn poll_task(&mut self, id: u64) {
102        let Some(mut task) = self.tasks.running.remove(&id) else { return };
103        if !self.contains(task.owner) {
104            return; // o dono foi liberado: a tarefa morre aqui
105        }
106        let waker = Waker::from(Arc::new(TaskWaker { id, poster: self.poster() }));
107        let mut cx = Context::from_waker(&waker);
108        let owner = task.owner;
109        let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task.future.as_mut().poll(&mut cx)));
110        match polled {
111            Ok(Poll::Ready(finish)) => {
112                self.guarded(owner, "spawn_local", finish);
113            }
114            Ok(Poll::Pending) => {
115                self.tasks.running.insert(id, task);
116            }
117            Err(payload) => {
118                let message = crate::exception::panic_message(payload.as_ref());
119                self.raise_exception(crate::Exception { message, path: self.path_of(owner), event: "spawn_local".into() });
120            }
121        }
122    }
123
124    /// As tarefas cujo dono saiu (o `free` chama).
125    pub(crate) fn drop_tasks_of(&mut self, doomed: &[ComponentId]) {
126        self.tasks.running.retain(|_, t| !doomed.contains(&t.owner));
127    }
128
129    /// Quantas tarefas `async` estão esperando.
130    pub fn running_tasks(&self) -> usize {
131        self.tasks.running.len()
132    }
133
134    /// Baixa `url` (HTTP GET) sem travar a tela, para usar dentro do
135    /// [`spawn_local`](Self::spawn_local): `let corpo = ui.http_get(url).await?`.
136    pub fn http_get(&mut self, url: &str) -> CallbackFuture<Result<Vec<u8>, String>> {
137        match self.services_mut().http.as_mut() {
138            Some(http) => from_callback(|done| http.get(url, done)),
139            None => CallbackFuture::ready(Err("sem o serviço de HTTP nesta plataforma".into())),
140        }
141    }
142
143    /// O diálogo de arquivos, esperando a escolha: `let arquivos = ui.choose_files(opções).await`.
144    pub fn choose_files(&mut self, options: crate::platform::FileDialogOptions) -> CallbackFuture<Vec<String>> {
145        match self.services_mut().file_dialogs.as_mut() {
146            Some(dialogs) => from_callback(|done| dialogs.show(options, done)),
147            None => CallbackFuture::ready(Vec::new()),
148        }
149    }
150
151    /// Pede as permissões, esperando a resposta do usuário.
152    pub fn request_permissions(
153        &mut self,
154        permissions: Vec<crate::platform::Permission>,
155    ) -> CallbackFuture<Vec<(crate::platform::Permission, crate::platform::PermissionState)>> {
156        match self.services_mut().permissions.as_mut() {
157            Some(service) => from_callback(|done| service.request(permissions, done)),
158            None => CallbackFuture::ready(Vec::new()),
159        }
160    }
161
162    /// Imprime, esperando o diálogo de impressão: `Ok(true)` impresso, `Ok(false)` cancelado.
163    pub fn print_pages(&mut self, title: &str, pages: crate::pages::PageSet) -> CallbackFuture<Result<bool, String>> {
164        match self.services_mut().printer.as_mut() {
165            Some(printer) => from_callback(|done| printer.print(title, pages, done)),
166            None => CallbackFuture::ready(Err("sem impressão nesta plataforma".into())),
167        }
168    }
169}
170
171/// Um `Future` para um serviço que responde por callback (de qualquer thread).
172pub struct CallbackFuture<T> {
173    shared: Arc<Mutex<(Option<T>, Option<Waker>)>>,
174}
175
176impl<T> CallbackFuture<T> {
177    /// Já com a resposta (o serviço não existe nesta plataforma, por exemplo).
178    pub fn ready(value: T) -> Self {
179        CallbackFuture { shared: Arc::new(Mutex::new((Some(value), None))) }
180    }
181}
182
183impl<T> Future for CallbackFuture<T> {
184    type Output = T;
185
186    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
187        let Ok(mut shared) = self.shared.lock() else { return Poll::Pending };
188        match shared.0.take() {
189            Some(value) => Poll::Ready(value),
190            None => {
191                shared.1 = Some(cx.waker().clone());
192                Poll::Pending
193            }
194        }
195    }
196}
197
198/// Liga um serviço de callback a um `Future`: `start` recebe o `done` que entrega o valor.
199pub fn from_callback<T: Send + 'static>(start: impl FnOnce(Box<dyn FnOnce(T) + Send>)) -> CallbackFuture<T> {
200    let shared: Arc<Mutex<(Option<T>, Option<Waker>)>> = Arc::new(Mutex::new((None, None)));
201    let answer = shared.clone();
202    start(Box::new(move |value| {
203        let waker = answer.lock().ok().and_then(|mut s| {
204            s.0 = Some(value);
205            s.1.take()
206        });
207        if let Some(waker) = waker {
208            waker.wake();
209        }
210    }));
211    CallbackFuture { shared }
212}