1use std::cell::{Cell, RefCell};
16use std::collections::{BTreeMap, HashSet, VecDeque};
17use std::future::Future;
18use std::pin::Pin;
19use std::rc::Rc;
20use std::sync::{Arc, Mutex};
21use std::task::{Context, Poll, Wake, Waker};
22use std::thread::ThreadId;
23use std::time::{Duration, Instant};
24
25use mitsuami_reactive::Owner;
26
27use crate::ui::Ui;
28
29type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
30
31struct Task {
33 future: LocalFuture,
34 owner: Option<Owner>,
35}
36
37thread_local! {
38 static CURRENT: RefCell<Option<crate::ui::WeakUi>> = const { RefCell::new(None) };
41}
42
43pub(crate) fn with_current<R>(ui: &Ui, f: impl FnOnce() -> R) -> R {
45 struct Restore(Option<crate::ui::WeakUi>);
48 impl Drop for Restore {
49 fn drop(&mut self) {
50 let previous = self.0.take();
51 let _ = CURRENT.try_with(|c| *c.borrow_mut() = previous);
52 }
53 }
54 let _restore = Restore(CURRENT.with(|c| c.replace(Some(ui.downgrade()))));
55 f()
56}
57
58pub trait Clock {
60 fn now(&self) -> Duration;
62}
63
64pub struct SystemClock(Instant);
66
67impl Default for SystemClock {
68 fn default() -> SystemClock {
69 SystemClock(Instant::now())
70 }
71}
72
73impl Clock for SystemClock {
74 fn now(&self) -> Duration {
75 self.0.elapsed()
76 }
77}
78
79#[derive(Default)]
81pub struct ManualClock(Cell<Duration>);
82
83impl ManualClock {
84 pub fn advance(&self, by: Duration) {
85 self.0.set(self.0.get() + by);
86 }
87}
88
89impl Clock for ManualClock {
90 fn now(&self) -> Duration {
91 self.0.get()
92 }
93}
94
95impl Clock for Rc<ManualClock> {
96 fn now(&self) -> Duration {
97 self.0.get()
98 }
99}
100
101#[derive(Default)]
104struct Queue {
105 order: VecDeque<u64>,
106 queued: HashSet<u64>,
107}
108
109impl Queue {
110 fn push(&mut self, id: u64) {
111 if self.queued.insert(id) {
112 self.order.push_back(id);
113 }
114 }
115
116 fn pop(&mut self) -> Option<u64> {
117 let id = self.order.pop_front()?;
118 self.queued.remove(&id);
119 Some(id)
120 }
121}
122
123struct ReadyQueue {
125 ready: Mutex<Queue>,
127 remote: Mutex<Queue>,
133 ui_thread: ThreadId,
134 wake_ui: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
136}
137
138struct TaskWaker {
139 id: u64,
140 queue: Arc<ReadyQueue>,
141}
142
143impl Wake for TaskWaker {
144 fn wake(self: Arc<Self>) {
145 self.wake_by_ref();
146 }
147
148 fn wake_by_ref(self: &Arc<Self>) {
149 let queue =
150 if std::thread::current().id() == self.queue.ui_thread { &self.queue.ready } else { &self.queue.remote };
151 queue.lock().unwrap().push(self.id);
152 let wake_ui = self.queue.wake_ui.lock().unwrap().clone();
153 if let Some(wake_ui) = wake_ui {
154 wake_ui();
155 }
156 }
157}
158
159pub(crate) struct Executor {
161 tasks: RefCell<BTreeMap<u64, Task>>,
162 next_task: Cell<u64>,
163 queue: Arc<ReadyQueue>,
164 clock: RefCell<Rc<dyn Clock>>,
165 timers: RefCell<BTreeMap<(Duration, u64), Waker>>,
167 next_timer: Cell<u64>,
168}
169
170impl Default for Executor {
171 fn default() -> Executor {
172 Executor {
173 tasks: RefCell::default(),
174 next_task: Cell::new(0),
175 queue: Arc::new(ReadyQueue {
176 ready: Mutex::default(),
177 remote: Mutex::default(),
178 ui_thread: std::thread::current().id(),
179 wake_ui: Mutex::default(),
180 }),
181 clock: RefCell::new(Rc::new(SystemClock::default())),
182 timers: RefCell::default(),
183 next_timer: Cell::new(0),
184 }
185 }
186}
187
188impl Executor {
189 pub(crate) fn spawn(&self, future: LocalFuture, owner: Option<Owner>) -> u64 {
193 let id = self.next_task.get();
194 self.next_task.set(id + 1);
195 self.tasks.borrow_mut().insert(id, Task { future, owner });
196 self.queue.ready.lock().unwrap().push(id);
197 id
198 }
199
200 pub(crate) fn cancel(&self, id: u64) {
201 let task = self.tasks.borrow_mut().remove(&id);
203 drop(task);
204 }
205
206 pub(crate) fn set_clock(&self, clock: Rc<dyn Clock>) {
207 *self.clock.borrow_mut() = clock;
208 }
209
210 pub(crate) fn now(&self) -> Duration {
211 self.clock.borrow().now()
212 }
213
214 pub(crate) fn set_wake_ui(&self, wake: Arc<dyn Fn() + Send + Sync>) {
215 *self.queue.wake_ui.lock().unwrap() = Some(wake);
216 }
217
218 fn add_timer(&self, deadline: Duration, waker: Waker) -> u64 {
219 let id = self.next_timer.get();
220 self.next_timer.set(id + 1);
221 self.timers.borrow_mut().insert((deadline, id), waker);
222 id
223 }
224
225 fn remove_timer(&self, deadline: Duration, id: u64) {
226 self.timers.borrow_mut().remove(&(deadline, id));
227 }
228
229 pub(crate) fn next_deadline(&self) -> Option<Duration> {
231 self.timers.borrow().keys().next().map(|(deadline, _)| *deadline)
232 }
233
234 pub(crate) fn run_ready(&self, ui: &Ui, remote: bool) -> bool {
237 if remote {
238 let woken = std::mem::take(&mut *self.queue.remote.lock().unwrap());
239 let mut ready = self.queue.ready.lock().unwrap();
240 for id in woken.order {
241 ready.push(id);
242 }
243 }
244 with_current(ui, || self.poll_ready())
245 }
246
247 fn poll_ready(&self) -> bool {
248 let now = self.now();
249 let due: Vec<Waker> = {
250 let mut timers = self.timers.borrow_mut();
251 let later = timers.split_off(&(now, u64::MAX));
252 std::mem::replace(&mut *timers, later).into_values().collect()
253 };
254 for waker in due {
255 waker.wake();
256 }
257 let mut ran = false;
258 let ready = self.queue.ready.lock().unwrap().order.len();
261 for _ in 0..ready {
262 let Some(id) = self.queue.ready.lock().unwrap().pop() else { break };
263 let Some(mut task) = self.tasks.borrow_mut().remove(&id) else { continue };
265 ran = true;
266 let waker = Waker::from(Arc::new(TaskWaker { id, queue: self.queue.clone() }));
267 let mut cx = Context::from_waker(&waker);
268 let pending = match task.owner {
269 Some(owner) if owner.is_alive() => owner.with(|| task.future.as_mut().poll(&mut cx)),
270 _ => task.future.as_mut().poll(&mut cx),
271 }
272 .is_pending();
273 if pending {
274 self.tasks.borrow_mut().insert(id, task);
275 }
276 }
277 ran
278 }
279
280 pub(crate) fn has_ready(&self) -> bool {
281 !self.queue.ready.lock().unwrap().order.is_empty()
282 }
283
284 pub(crate) fn task_count(&self) -> usize {
285 self.tasks.borrow().len()
286 }
287}
288
289#[derive(Clone)]
291pub struct TaskHandle {
292 id: u64,
293 ui: crate::ui::WeakUi,
294}
295
296impl TaskHandle {
297 pub(crate) fn new(id: u64, ui: crate::ui::WeakUi) -> TaskHandle {
298 TaskHandle { id, ui }
299 }
300
301 pub fn cancel(&self) {
303 if let Some(ui) = self.ui.upgrade() {
304 ui.executor().cancel(self.id);
305 }
306 }
307}
308
309pub(crate) fn current_ui() -> Ui {
310 CURRENT.with(|c| c.borrow().as_ref().and_then(|ui| ui.upgrade())).or_else(mitsuami_reactive::inject::<Ui>).expect(
311 "mitsuami: no Ui in scope. spawn_local/sleep must run inside a mounted view or a task \
312 (or use Ui::spawn_local / Ui::sleep directly)",
313 )
314}
315
316pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> TaskHandle {
325 let owner = Owner::current();
326 let guard = owner.map(|owner| owner.child());
330 let future = async move {
331 future.await;
332 if let Some(guard) = guard {
333 guard.dispose();
334 }
335 };
336 let handle = current_ui().spawn_in(future, owner);
337 if let Some(guard) = guard {
338 let cancel = handle.clone();
339 guard.with(|| mitsuami_reactive::on_cleanup(move || cancel.cancel()));
340 }
341 handle
342}
343
344pub fn spawn_blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> impl Future<Output = T> {
347 struct Shared<T> {
348 result: Option<T>,
349 waker: Option<Waker>,
350 }
351 let shared = Arc::new(Mutex::new(Shared { result: None, waker: None }));
352 let worker = shared.clone();
353 std::thread::spawn(move || {
354 let result = work();
355 let waker = {
356 let mut shared = worker.lock().unwrap();
357 shared.result = Some(result);
358 shared.waker.take()
359 };
360 if let Some(waker) = waker {
361 waker.wake();
362 }
363 });
364 std::future::poll_fn(move |cx| {
365 let mut shared = shared.lock().unwrap();
366 match shared.result.take() {
367 Some(result) => Poll::Ready(result),
368 None => {
369 shared.waker = Some(cx.waker().clone());
370 Poll::Pending
371 }
372 }
373 })
374}
375
376pub fn sleep(duration: Duration) -> Sleep {
382 current_ui().sleep(duration)
383}
384
385pub struct Sleep {
387 ui: Ui,
388 deadline: Duration,
389 timer: Option<u64>,
390}
391
392impl Sleep {
393 pub(crate) fn new(ui: Ui, duration: Duration) -> Sleep {
394 let deadline = ui.executor().now().saturating_add(duration);
396 Sleep { ui, deadline, timer: None }
397 }
398}
399
400impl Future for Sleep {
401 type Output = ();
402
403 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
404 let this = &mut *self;
405 let executor = this.ui.executor();
406 if let Some(id) = this.timer.take() {
407 executor.remove_timer(this.deadline, id);
408 }
409 if executor.now() >= this.deadline {
410 return Poll::Ready(());
411 }
412 this.timer = Some(executor.add_timer(this.deadline, cx.waker().clone()));
413 Poll::Pending
414 }
415}
416
417impl Drop for Sleep {
418 fn drop(&mut self) {
419 if let Some(id) = self.timer.take() {
420 self.ui.executor().remove_timer(self.deadline, id);
421 }
422 }
423}