1use std::cell::{Cell, RefCell};
14use std::collections::{BTreeMap, VecDeque};
15use std::future::Future;
16use std::pin::Pin;
17use std::rc::Rc;
18use std::sync::{Arc, Mutex};
19use std::task::{Context, Poll, Wake, Waker};
20use std::time::{Duration, Instant};
21
22use mitsuami_reactive::Owner;
23
24use crate::ui::Ui;
25
26type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
27
28struct Task {
30 future: LocalFuture,
31 owner: Option<Owner>,
32}
33
34thread_local! {
35 static CURRENT: RefCell<Option<crate::ui::WeakUi>> = const { RefCell::new(None) };
38}
39
40pub(crate) fn with_current<R>(ui: &Ui, f: impl FnOnce() -> R) -> R {
42 let previous = CURRENT.with(|c| c.replace(Some(ui.downgrade())));
43 let result = f();
44 CURRENT.with(|c| *c.borrow_mut() = previous);
45 result
46}
47
48pub(crate) fn in_current_scope<A>(f: impl Fn(A) + 'static) -> impl Fn(A) + 'static {
51 let owner = Owner::current();
52 move |arg| match owner {
53 Some(owner) if owner.is_alive() => owner.with(|| f(arg)),
54 _ => f(arg),
55 }
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)]
103struct ReadyQueue {
104 ready: Mutex<VecDeque<u64>>,
105 wake_ui: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
107}
108
109struct TaskWaker {
110 id: u64,
111 queue: Arc<ReadyQueue>,
112}
113
114impl Wake for TaskWaker {
115 fn wake(self: Arc<Self>) {
116 self.wake_by_ref();
117 }
118
119 fn wake_by_ref(self: &Arc<Self>) {
120 self.queue.ready.lock().unwrap().push_back(self.id);
121 let wake_ui = self.queue.wake_ui.lock().unwrap().clone();
122 if let Some(wake_ui) = wake_ui {
123 wake_ui();
124 }
125 }
126}
127
128pub(crate) struct Executor {
130 tasks: RefCell<BTreeMap<u64, Task>>,
131 next_task: Cell<u64>,
132 queue: Arc<ReadyQueue>,
133 clock: RefCell<Rc<dyn Clock>>,
134 timers: RefCell<BTreeMap<(Duration, u64), Waker>>,
136 next_timer: Cell<u64>,
137}
138
139impl Default for Executor {
140 fn default() -> Executor {
141 Executor {
142 tasks: RefCell::default(),
143 next_task: Cell::new(0),
144 queue: Arc::default(),
145 clock: RefCell::new(Rc::new(SystemClock::default())),
146 timers: RefCell::default(),
147 next_timer: Cell::new(0),
148 }
149 }
150}
151
152impl Executor {
153 pub(crate) fn spawn(&self, future: LocalFuture, owner: Option<Owner>) -> u64 {
157 let id = self.next_task.get();
158 self.next_task.set(id + 1);
159 self.tasks.borrow_mut().insert(id, Task { future, owner });
160 self.queue.ready.lock().unwrap().push_back(id);
161 id
162 }
163
164 pub(crate) fn cancel(&self, id: u64) {
165 let task = self.tasks.borrow_mut().remove(&id);
167 drop(task);
168 }
169
170 pub(crate) fn set_clock(&self, clock: Rc<dyn Clock>) {
171 *self.clock.borrow_mut() = clock;
172 }
173
174 pub(crate) fn now(&self) -> Duration {
175 self.clock.borrow().now()
176 }
177
178 pub(crate) fn set_wake_ui(&self, wake: Arc<dyn Fn() + Send + Sync>) {
179 *self.queue.wake_ui.lock().unwrap() = Some(wake);
180 }
181
182 fn add_timer(&self, deadline: Duration, waker: Waker) -> u64 {
183 let id = self.next_timer.get();
184 self.next_timer.set(id + 1);
185 self.timers.borrow_mut().insert((deadline, id), waker);
186 id
187 }
188
189 fn remove_timer(&self, deadline: Duration, id: u64) {
190 self.timers.borrow_mut().remove(&(deadline, id));
191 }
192
193 pub(crate) fn next_deadline(&self) -> Option<Duration> {
195 self.timers.borrow().keys().next().map(|(deadline, _)| *deadline)
196 }
197
198 pub(crate) fn run_ready(&self, ui: &Ui) -> bool {
201 with_current(ui, || self.poll_ready())
202 }
203
204 fn poll_ready(&self) -> bool {
205 let now = self.now();
206 let due: Vec<Waker> = {
207 let mut timers = self.timers.borrow_mut();
208 let later = timers.split_off(&(now, u64::MAX));
209 std::mem::replace(&mut *timers, later).into_values().collect()
210 };
211 for waker in due {
212 waker.wake();
213 }
214 let mut ran = false;
215 loop {
216 let Some(id) = self.queue.ready.lock().unwrap().pop_front() else { break };
217 let Some(mut task) = self.tasks.borrow_mut().remove(&id) else { continue };
219 ran = true;
220 let waker = Waker::from(Arc::new(TaskWaker { id, queue: self.queue.clone() }));
221 let mut cx = Context::from_waker(&waker);
222 let pending = match task.owner {
223 Some(owner) if owner.is_alive() => owner.with(|| task.future.as_mut().poll(&mut cx)),
224 _ => task.future.as_mut().poll(&mut cx),
225 }
226 .is_pending();
227 if pending {
228 self.tasks.borrow_mut().insert(id, task);
229 }
230 }
231 ran
232 }
233
234 pub(crate) fn has_ready(&self) -> bool {
235 !self.queue.ready.lock().unwrap().is_empty()
236 }
237
238 pub(crate) fn task_count(&self) -> usize {
239 self.tasks.borrow().len()
240 }
241}
242
243#[derive(Clone)]
245pub struct TaskHandle {
246 id: u64,
247 ui: crate::ui::WeakUi,
248}
249
250impl TaskHandle {
251 pub(crate) fn new(id: u64, ui: crate::ui::WeakUi) -> TaskHandle {
252 TaskHandle { id, ui }
253 }
254
255 pub fn cancel(&self) {
257 if let Some(ui) = self.ui.upgrade() {
258 ui.executor().cancel(self.id);
259 }
260 }
261}
262
263pub(crate) fn current_ui() -> Ui {
264 CURRENT.with(|c| c.borrow().as_ref().and_then(|ui| ui.upgrade())).or_else(mitsuami_reactive::inject::<Ui>).expect(
265 "mitsuami: no Ui in scope. spawn_local/sleep must run inside a mounted view or a task \
266 (or use Ui::spawn_local / Ui::sleep directly)",
267 )
268}
269
270pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> TaskHandle {
273 let handle = current_ui().spawn_in(future, Owner::current());
274 let cancel = handle.clone();
275 mitsuami_reactive::on_cleanup(move || cancel.cancel());
276 handle
277}
278
279pub fn spawn_blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> impl Future<Output = T> {
282 struct Shared<T> {
283 result: Option<T>,
284 waker: Option<Waker>,
285 }
286 let shared = Arc::new(Mutex::new(Shared { result: None, waker: None }));
287 let worker = shared.clone();
288 std::thread::spawn(move || {
289 let result = work();
290 let waker = {
291 let mut shared = worker.lock().unwrap();
292 shared.result = Some(result);
293 shared.waker.take()
294 };
295 if let Some(waker) = waker {
296 waker.wake();
297 }
298 });
299 std::future::poll_fn(move |cx| {
300 let mut shared = shared.lock().unwrap();
301 match shared.result.take() {
302 Some(result) => Poll::Ready(result),
303 None => {
304 shared.waker = Some(cx.waker().clone());
305 Poll::Pending
306 }
307 }
308 })
309}
310
311pub fn sleep(duration: Duration) -> Sleep {
313 current_ui().sleep(duration)
314}
315
316pub struct Sleep {
318 ui: Ui,
319 deadline: Duration,
320 timer: Option<u64>,
321}
322
323impl Sleep {
324 pub(crate) fn new(ui: Ui, duration: Duration) -> Sleep {
325 let deadline = ui.executor().now() + duration;
326 Sleep { ui, deadline, timer: None }
327 }
328}
329
330impl Future for Sleep {
331 type Output = ();
332
333 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
334 let this = &mut *self;
335 let executor = this.ui.executor();
336 if let Some(id) = this.timer.take() {
337 executor.remove_timer(this.deadline, id);
338 }
339 if executor.now() >= this.deadline {
340 return Poll::Ready(());
341 }
342 this.timer = Some(executor.add_timer(this.deadline, cx.waker().clone()));
343 Poll::Pending
344 }
345}
346
347impl Drop for Sleep {
348 fn drop(&mut self) {
349 if let Some(id) = self.timer.take() {
350 self.ui.executor().remove_timer(self.deadline, id);
351 }
352 }
353}