1use 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 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
34type 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
48struct 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 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 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 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; }
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 pub(crate) fn drop_tasks_of(&mut self, doomed: &[ComponentId]) {
126 self.tasks.running.retain(|_, t| !doomed.contains(&t.owner));
127 }
128
129 pub fn running_tasks(&self) -> usize {
131 self.tasks.running.len()
132 }
133
134 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 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 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 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
171pub struct CallbackFuture<T> {
173 shared: Arc<Mutex<(Option<T>, Option<Waker>)>>,
174}
175
176impl<T> CallbackFuture<T> {
177 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
198pub 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}