1use core::any::TypeId;
11use core::cell::{Cell, RefCell};
12use core::future::Future;
13use core::pin::Pin;
14use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use core::task::{Context, Poll, Waker};
16use core::time::Duration;
17use std::boxed::Box;
18use std::collections::{HashMap, VecDeque};
19use std::rc::Rc;
20use std::sync::{Arc, Mutex};
21use std::task::Wake;
22use std::vec::Vec;
23
24use crate::element::View;
25use crate::pod::{ActionScope, DragEvent, Handle, PodId, PodPool};
26
27use super::backend::SchedulerBackend;
28use super::scheduler::SchedulerCapabilities;
29use super::std_scheduler::{BackgroundExecutor, NativeStdScheduler, Timer};
30use super::task::{Task, TaskShared};
31
32#[derive(Copy, Clone)]
37struct ActiveEngineCtx {
38 pool_ptr: *mut PodPool,
39 now_ms: u32,
40}
41
42impl ActiveEngineCtx {
43 const EMPTY: Self = Self {
44 pool_ptr: core::ptr::null_mut(),
45 now_ms: 0,
46 };
47}
48
49std::thread_local! {
50 static ACTIVE_ENGINE_CTX: Cell<ActiveEngineCtx> = const { Cell::new(ActiveEngineCtx::EMPTY) };
51}
52
53struct ActiveEngineGuard {
54 prev: ActiveEngineCtx,
55}
56
57impl ActiveEngineGuard {
58 #[inline]
59 fn enter(pool: &mut PodPool, now_ms: u32) -> Self {
60 let prev = ACTIVE_ENGINE_CTX.with(|c| {
61 c.replace(ActiveEngineCtx {
62 pool_ptr: pool as *mut PodPool,
63 now_ms,
64 })
65 });
66 Self { prev }
67 }
68}
69
70impl Drop for ActiveEngineGuard {
71 #[inline]
72 fn drop(&mut self) {
73 ACTIVE_ENGINE_CTX.with(|c| c.set(self.prev));
74 }
75}
76
77type WakeUiFn = Arc<dyn Fn() + Send + Sync>;
82
83pub(crate) struct ForegroundShared {
84 next_id: AtomicU64,
85 ready_queue: Mutex<VecDeque<u64>>,
86 cancelled_ids: Mutex<Vec<u64>>,
87 wake_ui: Mutex<Option<WakeUiFn>>,
88 backend: Mutex<Arc<dyn SchedulerBackend>>,
89}
90
91impl ForegroundShared {
92 fn new(backend: Arc<dyn SchedulerBackend>) -> Arc<Self> {
93 Arc::new(Self {
94 next_id: AtomicU64::new(1),
95 ready_queue: Mutex::new(VecDeque::new()),
96 cancelled_ids: Mutex::new(Vec::new()),
97 wake_ui: Mutex::new(None),
98 backend: Mutex::new(backend),
99 })
100 }
101
102 fn backend(&self) -> Arc<dyn SchedulerBackend> {
103 let guard = self.backend.lock().unwrap_or_else(|e| e.into_inner());
104 Arc::clone(&guard)
105 }
106
107 fn set_backend(&self, backend: Arc<dyn SchedulerBackend>) {
108 let mut guard = self.backend.lock().unwrap_or_else(|e| e.into_inner());
109 *guard = backend;
110 }
111
112 fn set_wake_ui(&self, waker: WakeUiFn) {
113 let mut guard = self.wake_ui.lock().unwrap_or_else(|e| e.into_inner());
114 *guard = Some(waker);
115 }
116
117 fn notify_ui(&self) {
118 let cb = {
119 let guard = self.wake_ui.lock().unwrap_or_else(|e| e.into_inner());
120 guard.as_ref().map(Arc::clone)
121 };
122 if let Some(cb) = cb {
123 cb();
124 }
125 }
126
127 fn enqueue_ready(&self, task_id: u64) {
128 {
129 let mut q = self.ready_queue.lock().unwrap_or_else(|e| e.into_inner());
130 q.push_back(task_id);
131 }
132 self.notify_ui();
133 }
134
135 fn enqueue_cancel(&self, task_id: u64) {
136 {
137 let mut c = self.cancelled_ids.lock().unwrap_or_else(|e| e.into_inner());
138 c.push(task_id);
139 }
140 self.notify_ui();
141 }
142
143 fn has_ready(&self) -> bool {
144 let q = self.ready_queue.lock().unwrap_or_else(|e| e.into_inner());
145 !q.is_empty()
146 }
147
148 fn has_cancelled(&self) -> bool {
149 let c = self
150 .cancelled_ids
151 .lock()
152 .unwrap_or_else(|e| e.into_inner());
153 !c.is_empty()
154 }
155}
156
157struct FgTaskWaker {
158 shared: Arc<ForegroundShared>,
159 task_id: u64,
160 queued: Arc<AtomicBool>,
161 cancelled: Arc<AtomicBool>,
162}
163
164impl FgTaskWaker {
165 fn schedule(&self) {
166 if self.cancelled.load(Ordering::Acquire) {
167 return;
168 }
169 if !self.queued.swap(true, Ordering::AcqRel) {
170 self.shared.enqueue_ready(self.task_id);
171 }
172 }
173}
174
175impl Wake for FgTaskWaker {
176 fn wake(self: Arc<Self>) {
177 self.schedule();
178 }
179 fn wake_by_ref(self: &Arc<Self>) {
180 self.schedule();
181 }
182}
183
184struct FgTaskEntry {
185 future: Pin<Box<dyn Future<Output = ()>>>,
186 cancelled: Arc<AtomicBool>,
187 queued: Arc<AtomicBool>,
188}
189
190pub(crate) struct ForegroundLocal {
191 tasks: HashMap<u64, FgTaskEntry>,
192 defers: VecDeque<Box<dyn FnOnce(&mut ActionScope)>>,
193}
194
195impl ForegroundLocal {
196 fn new() -> Self {
197 Self {
198 tasks: HashMap::new(),
199 defers: VecDeque::new(),
200 }
201 }
202}
203
204pub struct ForegroundExecutor {
206 shared: Arc<ForegroundShared>,
207 local: Rc<RefCell<ForegroundLocal>>,
208}
209
210impl Default for ForegroundExecutor {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216impl ForegroundExecutor {
217 pub fn new() -> Self {
219 Self::with_backend(NativeStdScheduler::global())
220 }
221
222 pub fn with_backend(backend: Arc<dyn SchedulerBackend>) -> Self {
224 Self {
225 shared: ForegroundShared::new(backend),
226 local: Rc::new(RefCell::new(ForegroundLocal::new())),
227 }
228 }
229
230 pub fn set_backend(&self, backend: Arc<dyn SchedulerBackend>) {
232 self.shared.set_backend(backend);
233 }
234
235 #[inline]
237 pub fn backend(&self) -> Arc<dyn SchedulerBackend> {
238 self.shared.backend()
239 }
240
241 #[inline]
243 pub fn background_executor(&self) -> BackgroundExecutor {
244 BackgroundExecutor::with_backend(self.shared.backend())
245 }
246
247 #[inline]
249 pub fn scheduler_name(&self) -> &'static str {
250 self.shared.backend().name()
251 }
252
253 #[inline]
255 pub fn scheduler_capabilities(&self) -> SchedulerCapabilities {
256 self.shared.backend().capabilities()
257 }
258
259 pub fn set_wake_ui(&self, waker: impl Fn() + Send + Sync + 'static) {
261 self.shared.set_wake_ui(Arc::new(waker));
262 }
263
264 #[inline]
266 pub fn async_app(&self) -> AsyncApp {
267 AsyncApp {
268 shared: Arc::clone(&self.shared),
269 local: Rc::clone(&self.local),
270 }
271 }
272
273 pub fn spawn<T, F, Fut>(&self, f: F) -> Task<T>
275 where
276 T: 'static,
277 F: FnOnce(AsyncApp) -> Fut,
278 Fut: Future<Output = T> + 'static,
279 {
280 self.async_app().spawn(f)
281 }
282
283 pub fn defer<F>(&self, f: F)
285 where
286 F: FnOnce(&mut ActionScope) + 'static,
287 {
288 self.local.borrow_mut().defers.push_back(Box::new(f));
289 self.shared.notify_ui();
290 }
291
292 #[inline]
294 pub fn has_ready_work(&self) -> bool {
295 self.shared.has_ready() || !self.local.borrow().defers.is_empty()
296 }
297
298 #[inline]
300 pub(crate) fn has_work_to_poll(&self) -> bool {
301 self.has_ready_work() || self.shared.has_cancelled()
302 }
303
304 #[inline]
306 pub fn active_task_count(&self) -> usize {
307 self.local.borrow().tasks.len()
308 }
309
310 pub fn poll_ready(&self, pool: &mut PodPool, now_ms: u32) -> bool {
312 let _guard = ActiveEngineGuard::enter(pool, now_ms);
313 let mut did_work = false;
314
315 for _round in 0..64 {
317 let cancelled_batch: Vec<u64> = {
319 let mut c = self
320 .shared
321 .cancelled_ids
322 .lock()
323 .unwrap_or_else(|e| e.into_inner());
324 core::mem::take(&mut *c)
325 };
326 if !cancelled_batch.is_empty() {
327 let mut loc = self.local.borrow_mut();
328 for id in cancelled_batch {
329 loc.tasks.remove(&id);
330 }
331 }
332
333 let ready_batch: Vec<u64> = {
335 let mut q = self
336 .shared
337 .ready_queue
338 .lock()
339 .unwrap_or_else(|e| e.into_inner());
340 q.drain(..).collect()
341 };
342
343 let mut progressed_this_round = false;
344
345 for task_id in ready_batch {
346 let entry_opt = self.local.borrow_mut().tasks.remove(&task_id);
348 let Some(mut entry) = entry_opt else {
349 continue;
350 };
351 entry.queued.store(false, Ordering::Release);
352 if entry.cancelled.load(Ordering::Acquire) {
353 continue;
354 }
355
356 did_work = true;
357 progressed_this_round = true;
358
359 let waker = Waker::from(Arc::new(FgTaskWaker {
360 shared: Arc::clone(&self.shared),
361 task_id,
362 queued: Arc::clone(&entry.queued),
363 cancelled: Arc::clone(&entry.cancelled),
364 }));
365 let mut cx = Context::from_waker(&waker);
366 match entry.future.as_mut().poll(&mut cx) {
367 Poll::Ready(()) => {}
368 Poll::Pending => {
369 if !entry.cancelled.load(Ordering::Acquire) {
370 self.local.borrow_mut().tasks.insert(task_id, entry);
371 }
372 }
373 }
374 }
375
376 loop {
378 let next_defer = self.local.borrow_mut().defers.pop_front();
379 let Some(cb) = next_defer else {
380 break;
381 };
382 did_work = true;
383 progressed_this_round = true;
384 let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
385 if !ctx.pool_ptr.is_null() {
386 let pool_ref = unsafe { &mut *ctx.pool_ptr };
387 let mut acx = ActionScope::new(
388 PodId(u16::MAX),
389 pool_ref,
390 (0, 0),
391 DragEvent::default(),
392 ctx.now_ms,
393 )
394 .with_async_app(self.async_app());
395 cb(&mut acx);
396 acx.flush_signal_dirty_pods();
397 }
398 }
399
400 let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
402 if !ctx.pool_ptr.is_null() {
403 unsafe { &mut *ctx.pool_ptr }.flush_signal_dirty_pods();
404 }
405
406 if !progressed_this_round || !self.has_ready_work() {
407 break;
408 }
409 }
410
411 did_work
412 }
413}
414
415#[derive(Clone)]
424pub struct AsyncApp {
425 shared: Arc<ForegroundShared>,
426 local: Rc<RefCell<ForegroundLocal>>,
427}
428
429impl AsyncApp {
430 #[inline]
432 pub fn background_executor(&self) -> BackgroundExecutor {
433 BackgroundExecutor::with_backend(self.shared.backend())
434 }
435
436 #[inline]
438 pub fn background_spawn<T, Fut>(&self, fut: Fut) -> Task<T>
439 where
440 T: Send + 'static,
441 Fut: Future<Output = T> + Send + 'static,
442 {
443 self.background_executor().spawn(fut)
444 }
445
446 #[inline]
448 pub fn timer(&self, duration: Duration) -> Timer {
449 self.background_executor().timer(duration)
450 }
451
452 #[inline]
454 pub fn scheduler_name(&self) -> &'static str {
455 self.shared.backend().name()
456 }
457
458 pub fn spawn<T, F, Fut>(&self, f: F) -> Task<T>
460 where
461 T: 'static,
462 F: FnOnce(AsyncApp) -> Fut,
463 Fut: Future<Output = T> + 'static,
464 {
465 let task_id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
466 let cancelled = Arc::new(AtomicBool::new(false));
467 let queued = Arc::new(AtomicBool::new(true));
468
469 let shared_for_cancel = Arc::clone(&self.shared);
470 let on_cancel: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
471 shared_for_cancel.enqueue_cancel(task_id);
472 });
473 let task_shared = TaskShared::new(Arc::clone(&cancelled), Some(on_cancel));
474 let task_out = Arc::clone(&task_shared);
475
476 let fut = f(self.clone());
477 let wrapped = async move {
478 let output = fut.await;
479 if !task_out.is_cancelled() {
480 task_out.complete(output);
481 }
482 };
483
484 self.local.borrow_mut().tasks.insert(
485 task_id,
486 FgTaskEntry {
487 future: Box::pin(wrapped),
488 cancelled,
489 queued,
490 },
491 );
492 self.shared.enqueue_ready(task_id);
493 Task::from_shared(task_shared)
494 }
495
496 pub fn spawn_for<V, T, F, Fut>(&self, handle: Handle<V>, f: F) -> Task<T>
498 where
499 V: View,
500 T: 'static,
501 F: FnOnce(Handle<V>, AsyncApp) -> Fut,
502 Fut: Future<Output = T> + 'static,
503 {
504 self.spawn(move |cx| f(handle, cx))
505 }
506
507 #[inline]
509 pub fn defer<F>(&self, f: F)
510 where
511 F: FnOnce(&mut ActionScope) + 'static,
512 {
513 self.local.borrow_mut().defers.push_back(Box::new(f));
514 self.shared.notify_ui();
515 }
516
517 pub fn update<V: View, R>(
520 &mut self,
521 handle: Handle<V>,
522 f: impl FnOnce(&mut V, &mut ActionScope) -> R,
523 ) -> Option<R> {
524 let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
525 if ctx.pool_ptr.is_null() {
526 return None;
527 }
528 let pool = unsafe { &mut *ctx.pool_ptr };
529 let target_ptr = pool.acquire_raw_mut(handle.id, Some(handle.generation), TypeId::of::<V>())?;
530 let mut acx = ActionScope::new(
531 handle.id,
532 pool,
533 (0, 0),
534 DragEvent::default(),
535 ctx.now_ms,
536 )
537 .with_async_app(self.clone());
538 let view_ref = unsafe { &mut *(target_ptr as *mut V) };
539 let res = f(view_ref, &mut acx);
540 let skipped = acx.notify_skipped;
541 acx.release_view_borrow(handle.id);
542 if core::mem::size_of::<V>() > 0 && !skipped {
543 acx.notify();
544 }
545 acx.flush_signal_dirty_pods();
546 Some(res)
547 }
548
549 pub fn read<V: View, R>(&self, handle: Handle<V>, f: impl FnOnce(&V) -> R) -> Option<R> {
551 let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
552 if ctx.pool_ptr.is_null() {
553 return None;
554 }
555 let pool = unsafe { &*ctx.pool_ptr };
556 let view = pool.get(handle)?;
557 Some(f(view))
558 }
559
560 pub fn notify_handle<V: View>(&mut self, handle: Handle<V>) {
562 let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
563 if ctx.pool_ptr.is_null() {
564 return;
565 }
566 let pool = unsafe { &mut *ctx.pool_ptr };
567 if pool.get(handle).is_some() {
568 pool.mark_dirty(handle.id);
569 }
570 }
571
572 #[inline]
574 pub fn now_ms(&self) -> u32 {
575 ACTIVE_ENGINE_CTX.with(|c| c.get().now_ms)
576 }
577}