1use std::cell::{Ref as CellRef, RefCell, RefMut};
10use std::rc::{Rc, Weak};
11use std::time::Duration;
12
13use waft_embedder::{InertPlatform, PlatformRef};
14
15use crate::app::App;
16use crate::executor::{ExecutorHandle, ForegroundExecutor, Task};
17use crate::timers::{TimerMode, Timers};
18
19const CHECKPOINT_BUDGET: usize = 100_000;
22
23pub struct AppCell {
25 app: RefCell<App>,
26}
27
28impl AppCell {
29 pub fn new() -> Rc<AppCell> {
31 AppCell::with_platform(Rc::new(InertPlatform))
32 }
33
34 pub fn with_platform(platform: PlatformRef) -> Rc<AppCell> {
36 let executor = ForegroundExecutor::new(platform.dispatcher());
37 Rc::new_cyclic(|this| AppCell {
38 app: RefCell::new(App::build(this.clone(), platform, executor)),
39 })
40 }
41
42 pub fn borrow(&self) -> CellRef<'_, App> {
46 self.app.borrow()
47 }
48
49 pub fn borrow_mut(&self) -> RefMut<'_, App> {
56 self.app.borrow_mut()
57 }
58
59 pub fn checkpoint(&self) -> usize {
71 assert!(
72 self.app.try_borrow_mut().is_ok(),
73 "AppCell::checkpoint while the App is borrowed: release it first; each task \
74 borrows the App for its own steps"
75 );
76 let executor = self.borrow().executor_handle();
79 self.borrow_mut().begin_checkpoint();
80 let mut rounds = 0usize;
81 loop {
82 self.borrow_mut().free_dropped_objects();
83 self.borrow_mut().flush_entity_effects();
84 let had_microtasks = self.borrow().has_pending_microtasks();
85 if had_microtasks {
86 self.borrow_mut().drain_microtasks();
87 }
88 let polled = executor.poll_ready_tasks();
89 if !had_microtasks && polled == 0 {
90 self.borrow_mut().free_dropped_objects();
92 break;
93 }
94 rounds += 1;
95 assert!(
96 rounds <= CHECKPOINT_BUDGET,
97 "the checkpoint did not converge after {CHECKPOINT_BUDGET} rounds; are a \
98 microtask and a task queueing each other in a cycle?"
99 );
100 }
101 rounds
102 }
103
104 pub fn wake(&self) {
114 self.checkpoint();
115 self.borrow_mut().update_timer_wakeup();
116 }
117
118 pub fn elapse(&self, duration: Duration) {
130 let target = self.borrow().clock() + duration;
131 self.elapse_to_with(target, TimerMode::EachPeriod);
132 }
133
134 pub fn elapse_to(&self, target: Duration) {
145 self.elapse_to_with(target, TimerMode::CatchUp);
146 }
147
148 fn elapse_to_with(&self, target: Duration, mode: TimerMode) {
149 if mode == TimerMode::CatchUp && target <= self.borrow().clock() {
150 return;
151 }
152 self.checkpoint();
153 self.borrow_mut().begin_timer_turn();
154 if mode == TimerMode::CatchUp {
155 self.borrow_mut().advance_clock_to(target);
156 }
157 let mut fired = 0usize;
158 loop {
159 let fired_one = self.borrow_mut().fire_next_due(target, mode);
160 if !fired_one {
161 break;
162 }
163 fired += 1;
164 Timers::assert_fire_budget(fired);
165 self.checkpoint();
166 }
167 self.borrow_mut().advance_clock_to(target);
168 self.borrow_mut().update_timer_wakeup();
169 }
170}
171
172#[derive(Clone)]
177pub struct AsyncApp {
178 app: Weak<AppCell>,
179 executor: ExecutorHandle,
180}
181
182impl AsyncApp {
183 pub(crate) fn new(app: Weak<AppCell>, executor: ExecutorHandle) -> AsyncApp {
184 AsyncApp { app, executor }
185 }
186
187 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
194 let cell = self
195 .app
196 .upgrade()
197 .expect("the App was dropped while one of its tasks still runs");
198 let mut app = cell.app.try_borrow_mut().unwrap_or_else(|_| {
199 panic!(
200 "AsyncApp::update while the App is borrowed: tasks run only from \
201 AppCell::checkpoint, never from inside App code"
202 )
203 });
204 f(&mut app)
205 }
206
207 pub fn post(&self, f: impl FnOnce(&mut App) + 'static) {
216 if self.app.strong_count() == 0 {
217 return;
218 }
219 let cx = self.clone();
220 drop(self.executor.spawn(async move { cx.update(f) }));
222 }
223
224 pub fn run_in_background<T: Send + 'static>(
226 &self,
227 work: impl FnOnce() -> T + Send + 'static,
228 ) -> Task<T> {
229 self.executor.run_in_background(work)
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use std::cell::{Cell, RefCell};
236 use std::rc::Rc;
237 use std::sync::{Arc, Mutex};
238 use std::time::{Duration, Instant};
239
240 use waft_embedder::{Dispatcher, Platform, TargetPlatform, ViewId, ViewRef};
241
242 use crate::delayed;
243
244 use super::*;
245 use crate::change_notifier::Listener;
246 use crate::completer::Completer;
247 use crate::timers::Timer;
248
249 #[derive(Default)]
252 struct RecordingHost {
253 timer_wakeups: Mutex<Vec<Option<Instant>>>,
254 }
255
256 impl RecordingHost {
257 fn timer_wakeups(&self) -> Vec<Option<Instant>> {
258 self.timer_wakeups
259 .lock()
260 .expect("the wakeups are never poisoned: nothing runs under their lock")
261 .clone()
262 }
263 }
264
265 impl Dispatcher for RecordingHost {
266 fn wake_at(&self, timer_wakeup: Option<Instant>) {
267 self.timer_wakeups
268 .lock()
269 .expect("the wakeups are never poisoned: nothing runs under their lock")
270 .push(timer_wakeup);
271 }
272
273 fn wake_now(&self) {}
274
275 fn dispatch(&self, work: Box<dyn FnOnce() + Send>) {
276 work();
277 }
278 }
279
280 struct RecordingPlatform(Arc<RecordingHost>);
281
282 impl Platform for RecordingPlatform {
283 fn target_platform(&self) -> TargetPlatform {
284 TargetPlatform::Android
285 }
286
287 fn request_frame(&self, _view: ViewId) {}
288
289 fn now(&self) -> Instant {
290 Instant::now()
291 }
292
293 fn dispatcher(&self) -> Arc<dyn Dispatcher> {
294 Arc::clone(&self.0) as Arc<dyn Dispatcher>
295 }
296
297 fn views(&self) -> Vec<ViewRef> {
298 Vec::new()
299 }
300
301 fn view(&self, _id: ViewId) -> Option<ViewRef> {
302 None
303 }
304 }
305
306 fn app_on_a_recording_host() -> (Rc<AppCell>, Arc<RecordingHost>) {
307 let host = Arc::new(RecordingHost::default());
308 let cell = AppCell::with_platform(Rc::new(RecordingPlatform(Arc::clone(&host))));
309 (cell, host)
310 }
311
312 fn counter() -> Rc<Cell<u32>> {
313 Rc::new(Cell::new(0))
314 }
315
316 fn log() -> Rc<RefCell<Vec<&'static str>>> {
317 Rc::new(RefCell::new(Vec::new()))
318 }
319
320 #[test]
321 fn a_post_runs_at_the_next_checkpoint_even_when_made_while_borrowed() {
322 let cell = AppCell::new();
323 let ran = counter();
324 let cx = cell.borrow().to_async();
325 {
326 let _borrowed = cell.borrow_mut();
327 let ran = Rc::clone(&ran);
328 cx.post(move |_app| ran.set(ran.get() + 1));
329 }
330 assert_eq!(ran.get(), 0, "a post never runs inline");
331 cell.checkpoint();
332 assert_eq!(ran.get(), 1);
333 cell.checkpoint();
334 assert_eq!(ran.get(), 1, "a post runs once");
335 }
336
337 #[test]
338 fn a_post_after_the_app_is_gone_is_dropped() {
339 let cx = AppCell::new().borrow().to_async();
340 cx.post(|_app| panic!("the App is gone"));
341 }
342
343 #[test]
348 fn waking_for_a_ready_task_leaves_the_timer_wakeup_alone() {
349 let (cell, host) = app_on_a_recording_host();
350 Timer::new(
351 &mut cell.borrow_mut(),
352 Duration::from_millis(50),
353 Listener::new(|_app| {}),
354 );
355 let wakeups = host.timer_wakeups();
356 assert_eq!(wakeups.len(), 1, "the timer sets its wakeup");
357 assert!(wakeups[0].is_some_and(|wakeup| wakeup > Instant::now()));
358
359 host.wake_now();
361 cell.wake();
362
363 assert_eq!(
364 host.timer_wakeups(),
365 wakeups,
366 "the wake neither cleared the timer wakeup nor made the app set it again"
367 );
368 }
369
370 #[test]
373 fn cancelling_the_last_timer_tells_the_host_no_timer_is_waiting() {
374 let (cell, host) = app_on_a_recording_host();
375 let timer = Timer::new(
376 &mut cell.borrow_mut(),
377 Duration::from_millis(50),
378 Listener::new(|_app| {}),
379 );
380 timer.cancel(&mut cell.borrow_mut());
381 let wakeups = host.timer_wakeups();
382 assert_eq!(wakeups.len(), 2, "the cancel changes the timer wakeup");
383 assert_eq!(
384 wakeups[1], None,
385 "with no timer left the host is told to stop waiting for one"
386 );
387 }
388
389 #[test]
390 fn a_wake_runs_the_checkpoint() {
391 let cell = AppCell::new();
392 let ran = counter();
393 let cx = cell.borrow().to_async();
394 {
395 let ran = Rc::clone(&ran);
396 cx.post(move |_app| ran.set(ran.get() + 1));
397 }
398 cell.wake();
399 assert_eq!(ran.get(), 1);
400 }
401
402 #[test]
403 fn a_spawned_continuation_runs_at_the_checkpoint_not_inline() {
404 let cell = AppCell::new();
405 let ran = counter();
406 {
407 let seen = ran.clone();
408 cell.borrow()
409 .spawn(async move |_cx| seen.set(seen.get() + 1));
410 assert_eq!(ran.get(), 0, "spawn never polls inline");
411 }
412 cell.checkpoint();
413 assert_eq!(ran.get(), 1);
414 }
415
416 #[test]
417 fn a_task_reaches_the_app_through_update() {
418 let cell = AppCell::new();
419 let handle_ref = cell.borrow_mut().create(3u32);
420 let handle = handle_ref.handle();
421 cell.borrow().spawn(async move |cx| {
422 cx.update(|app| *app.get_mut(handle) += 4);
423 });
424 cell.checkpoint();
425 assert_eq!(*cell.borrow().get(handle), 7);
426 }
427
428 #[test]
429 fn awaiting_a_completer_resumes_at_the_checkpoint_after_completion() {
430 let cell = AppCell::new();
431 let completer: Completer<u32> = Completer::new();
432 let future = completer.future();
433 let seen = counter();
434 let out = seen.clone();
435 cell.borrow().spawn(async move |_cx| out.set(future.await));
436 cell.checkpoint();
437 assert_eq!(seen.get(), 0, "pending: the waker is parked");
438
439 completer.complete(&mut cell.borrow_mut(), 7);
440 assert_eq!(seen.get(), 0, "completion wakes; it does not poll inline");
441 cell.checkpoint();
442 assert_eq!(seen.get(), 7);
443 }
444
445 #[test]
446 fn a_completer_resolves_every_listener() {
447 let cell = AppCell::new();
448 let completer: Completer<u32> = Completer::new();
449 let seen = counter();
450 for _ in 0..3 {
451 let future = completer.future();
452 let out = seen.clone();
453 cell.borrow().spawn(async move |_cx| {
454 let value = future.await;
455 out.set(out.get() + value);
456 });
457 }
458 cell.checkpoint();
459 completer.complete(&mut cell.borrow_mut(), 5);
460 cell.checkpoint();
461 assert_eq!(seen.get(), 15);
462 }
463
464 #[test]
465 fn a_task_awaited_as_a_task_yields_its_result() {
466 let cell = AppCell::new();
467 let seen = counter();
468 let out = seen.clone();
469 let inner = cell.borrow().spawn(async move |_cx| 40u32);
470 cell.borrow()
471 .spawn(async move |_cx| out.set(inner.await + 2));
472 cell.checkpoint();
473 assert_eq!(seen.get(), 42);
474 }
475
476 #[test]
479 fn a_checkpoint_runs_what_its_continuations_queue() {
480 let cell = AppCell::new();
481 let events = log();
482 let completer: Completer<()> = Completer::new();
483 let future = completer.future();
484 let seen = events.clone();
485 cell.borrow().spawn(async move |cx| {
486 future.await;
487 seen.borrow_mut().push("task");
488 let seen = seen.clone();
489 cx.update(|app| {
490 app.schedule_microtask(Listener::new(move |_app| {
491 seen.borrow_mut().push("microtask from the task")
492 }))
493 });
494 });
495 cell.checkpoint();
496
497 completer.complete(&mut cell.borrow_mut(), ());
498 cell.checkpoint();
499 assert_eq!(*events.borrow(), ["task", "microtask from the task"]);
500 assert!(!cell.borrow().has_pending_microtasks());
501 }
502
503 #[test]
504 fn elapse_lets_a_task_chain_timers_within_one_call() {
505 let cell = AppCell::new();
506 let seen = counter();
507 let out = seen.clone();
508 cell.borrow().spawn(async move |cx| {
509 let first = cx.update(|app| delayed(app, Duration::from_millis(10)));
510 first.await;
511 out.set(1);
512 let second = cx.update(|app| delayed(app, Duration::from_millis(10)));
513 second.await;
514 out.set(2);
515 });
516 cell.checkpoint();
517 cell.elapse(Duration::from_millis(15));
518 assert_eq!(
519 seen.get(),
520 1,
521 "the first timer fired, the second is still due"
522 );
523 cell.elapse(Duration::from_millis(10));
524 assert_eq!(
525 seen.get(),
526 2,
527 "the second timer was scheduled by the resumed task"
528 );
529 }
530
531 #[test]
532 fn dropping_the_cell_releases_queued_and_pending_tasks() {
533 let cell = AppCell::new();
534 let token = Rc::new(());
535 let queued = token.clone();
536 cell.borrow().spawn(async move |_cx| drop(queued));
537 let completer_ref = cell.borrow_mut().create(Completer::<()>::new());
538 let completer = completer_ref.handle();
539 let future = cell.borrow().get(completer).future();
540 let pending = token.clone();
541 cell.borrow().spawn(async move |_cx| {
542 future.await;
543 drop(pending);
544 });
545 assert_eq!(Rc::strong_count(&token), 3);
546
547 drop(cell);
548 assert_eq!(
549 Rc::strong_count(&token),
550 1,
551 "the queued and the pending task's futures were dropped with the App"
552 );
553 }
554
555 #[test]
556 #[should_panic(expected = "AppCell::checkpoint while the App is borrowed")]
557 fn a_checkpoint_while_borrowed_panics() {
558 let cell = AppCell::new();
559 let _app = cell.borrow_mut();
560 cell.checkpoint();
561 }
562
563 #[test]
564 fn then_runs_on_the_microtask_queue_after_completion() {
565 let cell = AppCell::new();
566 let completer: Completer<u32> = Completer::new();
567 let seen = counter();
568 {
569 let mut app = cell.borrow_mut();
570 let out = seen.clone();
571 completer
572 .future()
573 .then(&mut app, move |_app, value| out.set(value));
574 completer.complete(&mut app, 9);
575 assert_eq!(seen.get(), 0, "a listener never runs inline");
576 app.drain_microtasks();
577 assert_eq!(seen.get(), 9, "a listener is a microtask");
578 }
579 let later = counter();
580 {
581 let mut app = cell.borrow_mut();
582 let out = later.clone();
583 completer
584 .future()
585 .then(&mut app, move |_app, value| out.set(value));
586 assert_eq!(later.get(), 0, "even on a resolved future");
587 }
588 cell.checkpoint();
589 assert_eq!(later.get(), 9);
590 }
591}