1use std::cell::{Cell, RefCell};
13use std::collections::HashMap;
14use std::future::Future;
15use std::pin::Pin;
16use std::rc::Rc;
17use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
18
19use day_spec::present::{PresentResult, PresentSpec};
20
21use crate::with_tree;
22
23type LocalFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
24
25day_reactive::tls_slots! {
26 present;
27 static TASKS: RefCell<HashMap<u64, Option<LocalFuture>>> = RefCell::new(HashMap::new());
29 static NEXT_TASK: Cell<u64> = const { Cell::new(1) };
30 static SHUTTING_DOWN: Cell<bool> = const { Cell::new(false) };
31 static REWAKE: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
34 static PENDING: RefCell<HashMap<u64, PendingEntry>> = RefCell::new(HashMap::new());
35 static NEXT_REQ: Cell<u64> = const { Cell::new(1) };
36 static PRESENTATION_MODE: Cell<Option<PresentationMode>> = const { Cell::new(None) };
37}
38
39pub use day_spec::present::app_temp_dir;
42
43#[must_use]
47pub fn sleep(ms: u32) -> Sleep {
48 Sleep {
49 ms,
50 scheduled: false,
51 shared: std::sync::Arc::new(SleepShared {
52 done: std::sync::atomic::AtomicBool::new(false),
53 waker: std::sync::Mutex::new(None),
54 }),
55 }
56}
57
58struct SleepShared {
59 done: std::sync::atomic::AtomicBool,
60 waker: std::sync::Mutex<Option<Waker>>,
61}
62
63pub struct Sleep {
65 ms: u32,
66 scheduled: bool,
67 shared: std::sync::Arc<SleepShared>,
68}
69
70impl Future for Sleep {
71 type Output = ();
72
73 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
74 use std::sync::atomic::Ordering;
75 if self.shared.done.load(Ordering::Acquire) {
76 return Poll::Ready(());
77 }
78 if let Ok(mut w) = self.shared.waker.lock() {
79 *w = Some(cx.waker().clone());
80 }
81 if !self.scheduled {
82 self.scheduled = true;
83 let shared = self.shared.clone();
84 day_reactive::on_main_delayed(self.ms, move || {
85 shared.done.store(true, Ordering::Release);
86 if let Ok(mut w) = shared.waker.lock()
87 && let Some(w) = w.take()
88 {
89 w.wake();
90 }
91 });
92 }
93 Poll::Pending
94 }
95}
96
97struct PendingEntry {
98 shared: Rc<PendingShared>,
99 spec: PresentSpec,
100 native: bool,
101}
102
103struct PendingShared {
104 result: RefCell<Option<PresentResult>>,
105 waker: RefCell<Option<Waker>>,
106}
107
108#[derive(Clone, Copy)]
117pub struct TaskHandle {
118 id: u64,
119 _not_send: std::marker::PhantomData<*const ()>,
120}
121
122impl TaskHandle {
123 pub fn abort(self) {
126 let fut = TASKS.try_with(|t| t.borrow_mut().remove(&self.id));
132 drop(fut);
133 }
134
135 #[must_use]
137 pub fn is_finished(self) -> bool {
138 !TASKS
139 .try_with(|t| t.borrow().contains_key(&self.id))
140 .unwrap_or(false)
141 }
142}
143
144pub fn task(fut: impl Future<Output = ()> + 'static) -> TaskHandle {
151 if SHUTTING_DOWN.try_with(Cell::get).unwrap_or(true) {
152 return TaskHandle {
153 id: 0,
154 _not_send: std::marker::PhantomData,
155 };
156 }
157 let id = NEXT_TASK.with(|c| {
158 let v = c.get();
159 c.set(v + 1);
160 v
161 });
162 TASKS.with(|t| t.borrow_mut().insert(id, Some(Box::pin(fut))));
163 poll_task(id);
164 TaskHandle {
165 id,
166 _not_send: std::marker::PhantomData,
167 }
168}
169
170pub(crate) fn shutdown_tasks() {
173 if SHUTTING_DOWN
174 .try_with(|closing| closing.replace(true))
175 .unwrap_or(true)
176 {
177 return;
178 }
179 let tasks = TASKS.with(|tasks| std::mem::take(&mut *tasks.borrow_mut()));
180 REWAKE.with(|wake| wake.borrow_mut().clear());
181 for future in tasks.into_values().flatten() {
182 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(future))).is_err() {
183 log::warn!("an async task panicked during shutdown; continuing task cleanup");
184 day_reactive::recover_from_panic();
185 crate::notify_contained_panic();
186 }
187 }
188}
189
190fn poll_task(id: u64) {
191 if SHUTTING_DOWN.try_with(Cell::get).unwrap_or(true) {
192 return;
193 }
194 let fut = TASKS.with(|t| {
195 t.borrow_mut()
196 .get_mut(&id)
197 .and_then(std::option::Option::take)
198 });
199 let Some(mut fut) = fut else {
200 let live = TASKS.with(|t| t.borrow().contains_key(&id));
204 if live {
205 REWAKE.with(|r| r.borrow_mut().push(id));
206 }
207 return;
208 };
209 let waker = task_waker(id);
210 let mut cx = Context::from_waker(&waker);
211 loop {
212 match fut.as_mut().poll(&mut cx) {
213 Poll::Ready(()) => {
214 TASKS.with(|t| {
215 t.borrow_mut().remove(&id);
216 });
217 REWAKE.with(|r| r.borrow_mut().retain(|w| *w != id));
218 return;
219 }
220 Poll::Pending => {
221 let again = REWAKE.with(|r| {
222 let mut r = r.borrow_mut();
223 let had = r.contains(&id);
224 r.retain(|w| *w != id);
225 had
226 });
227 if !again {
228 TASKS.with(|t| {
229 if let Some(slot) = t.borrow_mut().get_mut(&id) {
230 *slot = Some(fut);
231 }
232 });
233 return;
234 }
235 }
236 }
237 }
238}
239
240fn task_waker(id: u64) -> Waker {
242 unsafe { Waker::from_raw(raw_waker(id as usize as *const ())) }
245}
246
247fn raw_waker(data: *const ()) -> RawWaker {
248 RawWaker::new(data, &VTABLE)
249}
250
251static VTABLE: RawWakerVTable = RawWakerVTable::new(
252 raw_waker, |d| wake_task(d as usize as u64),
254 |d| wake_task(d as usize as u64),
255 |_| {},
256);
257
258fn wake_task(id: u64) {
259 day_reactive::on_main(move || poll_task(id));
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum PresentationMode {
270 Native,
271 Scripted,
272}
273
274#[must_use]
276pub fn presentation_mode() -> PresentationMode {
277 PRESENTATION_MODE.with(|slot| {
278 if let Some(mode) = slot.get() {
279 return mode;
280 }
281 let mode = if std::env::var("DAY_TEST_DIALOGS").as_deref() == Ok("scripted") {
282 PresentationMode::Scripted
283 } else {
284 PresentationMode::Native
285 };
286 slot.set(Some(mode));
287 mode
288 })
289}
290
291pub fn init_presentation_mode(mode: PresentationMode) {
294 PRESENTATION_MODE.with(|slot| {
295 if slot.get().is_none() {
296 slot.set(Some(mode));
297 }
298 });
299}
300
301pub fn set_presentation_mode(mode: PresentationMode) -> Result<(), &'static str> {
308 if mode != presentation_mode() && PENDING.with(|p| !p.borrow().is_empty()) {
309 return Err("answer pending dialogs with respond before changing dialog_mode");
310 }
311 PRESENTATION_MODE.with(|slot| slot.set(Some(mode)));
312 Ok(())
313}
314
315#[must_use]
319pub fn present(spec: PresentSpec) -> PresentFuture {
320 let req = NEXT_REQ.with(|c| {
321 let v = c.get();
322 c.set(v + 1);
323 v
324 });
325 PresentFuture {
326 req,
327 spec: Some(spec),
328 shared: Rc::new(PendingShared {
329 result: RefCell::new(None),
330 waker: RefCell::new(None),
331 }),
332 presented: false,
333 }
334}
335
336pub struct PresentFuture {
337 req: u64,
338 spec: Option<PresentSpec>,
339 shared: Rc<PendingShared>,
340 presented: bool,
341}
342
343impl Future for PresentFuture {
344 type Output = PresentResult;
345
346 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<PresentResult> {
347 if let Some(result) = self.shared.result.borrow_mut().take() {
348 return Poll::Ready(result);
349 }
350 if !self.presented {
351 self.presented = true;
352 let req = self.req;
353 let spec = self.spec.take().expect("present spec");
354 let native = presentation_mode() == PresentationMode::Native;
355 PENDING.with(|p| {
356 p.borrow_mut().insert(
357 req,
358 PendingEntry {
359 shared: self.shared.clone(),
360 spec: spec.clone(),
361 native,
362 },
363 )
364 });
365 if native {
366 with_tree(|t| t.present(req, &spec));
367 }
368 }
369 *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
370 Poll::Pending
371 }
372}
373
374pub fn resolve_presentation(req: u64, result: PresentResult) {
377 let entry = PENDING.with(|p| p.borrow_mut().remove(&req));
378 if let Some(entry) = entry {
379 *entry.shared.result.borrow_mut() = Some(result);
380 if let Some(waker) = entry.shared.waker.borrow_mut().take() {
381 waker.wake();
382 }
383 }
384}
385
386pub fn respond_presentation(req: u64, result: PresentResult) -> bool {
392 let native = PENDING.with(|p| p.borrow().get(&req).map(|entry| entry.native));
393 let Some(native) = native else {
394 return false;
395 };
396 resolve_presentation(req, result);
397 if native {
398 with_tree(|t| t.dismiss(req));
399 }
400 true
401}
402
403#[must_use]
405pub fn pending_presentation() -> Option<(u64, PresentSpec)> {
406 PENDING.with(|p| {
407 p.borrow()
408 .iter()
409 .max_by_key(|(req, _)| **req)
410 .map(|(req, entry)| (*req, entry.spec.clone()))
411 })
412}
413
414#[cfg(test)]
419mod task_tests {
420 use super::*;
421 use std::cell::Cell;
422 use std::task::Waker;
423
424 #[test]
425 fn scripted_dialogs_preserve_answers_without_calling_the_toolkit() {
426 use day_spec::present::{ButtonRole, PresentButton};
427 let (toolkit, probe) = day_mock::MockToolkit::new();
428 crate::tree::install_tree(Box::new(crate::Tree::new(
429 toolkit,
430 day_mock::MockHandle(0),
431 day_spec::Size::new(100.0, 100.0),
432 )));
433 let cases = [
434 (
435 PresentSpec::Dialog {
436 title: "confirm".into(),
437 message: None,
438 buttons: vec![PresentButton {
439 label: "Yes".into(),
440 role: ButtonRole::Default,
441 }],
442 sheet: false,
443 },
444 PresentResult::Button(0),
445 ),
446 (
447 PresentSpec::Prompt {
448 title: "prompt".into(),
449 message: None,
450 placeholder: String::new(),
451 initial: String::new(),
452 ok: "OK".into(),
453 cancel: "Cancel".into(),
454 },
455 PresentResult::Text("Ada".into()),
456 ),
457 (
458 PresentSpec::OpenFile {
459 title: "open".into(),
460 filters: vec![],
461 multiple: false,
462 },
463 PresentResult::Files(vec!["fixture.txt".into()]),
464 ),
465 (
466 PresentSpec::OpenFile {
467 title: "open many".into(),
468 filters: vec![],
469 multiple: true,
470 },
471 PresentResult::Files(vec!["a.txt".into(), "b.txt".into()]),
472 ),
473 (
474 PresentSpec::OpenFolder {
475 title: "folder".into(),
476 },
477 PresentResult::Files(vec!["music".into()]),
478 ),
479 (
480 PresentSpec::SaveFile {
481 title: "save".into(),
482 suggested_name: "copy.txt".into(),
483 src_path: "staged.txt".into(),
484 filters: vec![],
485 },
486 PresentResult::Files(vec!["copy.txt".into()]),
487 ),
488 ];
489 let mut cx = Context::from_waker(Waker::noop());
490 for mode in [PresentationMode::Native, PresentationMode::Scripted] {
491 set_presentation_mode(mode).unwrap();
492 init_presentation_mode(PresentationMode::Native);
494 assert_eq!(presentation_mode(), mode);
495 for (spec, answer) in &cases {
496 for result in [answer.clone(), PresentResult::Dismissed] {
497 probe.clear_log();
498 let mut future = Box::pin(present(spec.clone()));
499 assert!(future.as_mut().poll(&mut cx).is_pending());
500 let (req, pending) = pending_presentation().unwrap();
501 assert_eq!(&pending, spec);
502 let other = if mode == PresentationMode::Native {
503 PresentationMode::Scripted
504 } else {
505 PresentationMode::Native
506 };
507 assert!(set_presentation_mode(other).is_err());
508 assert_eq!(presentation_mode(), mode);
509 assert!(respond_presentation(req, result.clone()));
510 resolve_presentation(req, PresentResult::Dismissed);
512 assert!(!respond_presentation(req, PresentResult::Dismissed));
513 assert_eq!(future.as_mut().poll(&mut cx), Poll::Ready(result));
514 assert!(pending_presentation().is_none());
515 let log = probe.log();
516 if mode == PresentationMode::Native {
517 assert_eq!(log.len(), 2, "{log:?}");
518 assert!(log[0].starts_with("present req="));
519 assert!(log[1].starts_with("dismiss req="));
520 } else {
521 assert!(
522 log.is_empty(),
523 "scripted requests reached the toolkit: {log:?}"
524 );
525 }
526 }
527 }
528 }
529 set_presentation_mode(PresentationMode::Native).unwrap();
530 crate::uninstall_tree();
531 }
532
533 fn init() {
537 day_reactive::install_main_poster(|f| f());
538 }
539
540 struct DropFlag(Rc<Cell<bool>>);
542 impl Drop for DropFlag {
543 fn drop(&mut self) {
544 self.0.set(true);
545 }
546 }
547
548 fn pending_forever(flag: Rc<Cell<bool>>) -> impl Future<Output = ()> {
549 let guard = DropFlag(flag);
550 std::future::poll_fn(move |_| {
551 let _ = &guard;
552 Poll::Pending
553 })
554 }
555
556 #[test]
557 fn task_runs_to_completion() {
558 init();
559 let ran = Rc::new(Cell::new(false));
560 let r = ran.clone();
561 let h = task(async move { r.set(true) });
562 assert!(ran.get());
563 assert!(h.is_finished());
564 }
565
566 #[test]
567 fn abort_drops_pending_future() {
568 init();
569 let dropped = Rc::new(Cell::new(false));
570 let h = task(pending_forever(dropped.clone()));
571 assert!(!h.is_finished());
572 assert!(!dropped.get());
573 h.abort();
574 assert!(dropped.get());
575 assert!(h.is_finished());
576 }
577
578 #[test]
579 fn abort_after_completion_is_noop() {
580 init();
581 let h = task(async {});
582 assert!(h.is_finished());
583 h.abort();
584 assert!(h.is_finished());
585 }
586
587 #[test]
591 fn abort_self_while_polling() {
592 init();
593 let handle: Rc<Cell<Option<TaskHandle>>> = Rc::new(Cell::new(None));
594 let dropped = Rc::new(Cell::new(false));
595 let waker_slot: Rc<RefCell<Option<Waker>>> = Rc::new(RefCell::new(None));
596
597 let h_cell = handle.clone();
598 let w_slot = waker_slot.clone();
599 let guard = DropFlag(dropped.clone());
600 let h = task(std::future::poll_fn(move |cx| {
601 let _ = &guard;
602 match h_cell.get() {
603 None => {
604 *w_slot.borrow_mut() = Some(cx.waker().clone());
605 Poll::Pending
606 }
607 Some(h) => {
608 h.abort();
609 Poll::Pending
610 }
611 }
612 }));
613 handle.set(Some(h));
614 assert!(!dropped.get());
615 let waker = waker_slot
616 .borrow_mut()
617 .take()
618 .expect("waker from first poll");
619 waker.wake(); assert!(dropped.get());
621 assert!(h.is_finished());
622 }
623
624 #[test]
627 fn abort_reentrancy_from_drop() {
628 struct SpawnOnDrop;
629 impl Drop for SpawnOnDrop {
630 fn drop(&mut self) {
631 task(async {});
632 }
633 }
634 init();
635 let guard = SpawnOnDrop;
636 let h = task(std::future::poll_fn(move |_| {
637 let _ = &guard;
638 Poll::<()>::Pending
639 }));
640 h.abort();
641 assert!(h.is_finished());
642 }
643
644 #[test]
645 fn termination_drops_tasks_before_reactive_tls_and_dependency_shutdown() {
646 const CHILD: &str = "DAY_TASK_SHUTDOWN_CHILD";
648 if std::env::var_os(CHILD).is_some() {
649 std::thread::spawn(|| {
650 struct Updating(day_reactive::Signal<bool>);
651 impl Drop for Updating {
652 fn drop(&mut self) {
653 self.0.set(false);
654 }
655 }
656 init();
657 assert!(!crate::has_tree()); let active = day_reactive::Signal::new(true);
659 let guard = Updating(active);
660 let handle = task(std::future::poll_fn(move |_| {
661 let _ = &guard;
662 Poll::Pending
663 }));
664 crate::on_lifecycle(day_spec::Lifecycle::WillTerminate, move || {
665 assert!(!active.get_untracked());
666 assert!(handle.is_finished());
667 });
668 crate::dispatch_lifecycle(day_spec::Lifecycle::WillTerminate);
669 crate::dispatch_lifecycle(day_spec::Lifecycle::WillTerminate);
670 assert!(!active.get_untracked());
671 })
672 .join()
673 .unwrap();
674 return;
675 }
676 let output = std::process::Command::new(std::env::current_exe().unwrap())
677 .args([
678 "--exact",
679 "present::task_tests::termination_drops_tasks_before_reactive_tls_and_dependency_shutdown",
680 "--nocapture",
681 ])
682 .env(CHILD, "1")
683 .output()
684 .unwrap();
685 assert!(
686 output.status.success(),
687 "{}",
688 String::from_utf8_lossy(&output.stderr)
689 );
690 assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
691 }
692
693 #[test]
694 fn shutdown_rejects_reentrant_tasks_and_late_wakes() {
695 struct SpawnOnDrop(Rc<Cell<bool>>);
696 impl Drop for SpawnOnDrop {
697 fn drop(&mut self) {
698 let polled = self.0.clone();
699 let h = task(async move { polled.set(true) });
700 assert!(h.is_finished());
701 h.abort();
702 }
703 }
704 init();
705 let polled = Rc::new(Cell::new(false));
706 let guard = SpawnOnDrop(polled.clone());
707 let wake = Rc::new(RefCell::new(None));
708 let saved = wake.clone();
709 let polls = Rc::new(Cell::new(0));
710 let count = polls.clone();
711 let h = task(std::future::poll_fn(move |cx| {
712 let _ = &guard;
713 count.set(count.get() + 1);
714 *saved.borrow_mut() = Some(cx.waker().clone());
715 Poll::Pending
716 }));
717 shutdown_tasks();
718 wake.borrow_mut().take().unwrap().wake();
719 shutdown_tasks();
720 assert!(h.is_finished());
721 assert!(!polled.get());
722 assert_eq!(polls.get(), 1);
723 assert!(TASKS.with(|tasks| tasks.borrow().is_empty()));
724 }
725
726 #[test]
727 fn shutdown_continues_after_a_task_destructor_panics() {
728 struct Panics;
729 impl Drop for Panics {
730 fn drop(&mut self) {
731 panic!("synthetic task destructor failure");
732 }
733 }
734 init();
735 let guard = Panics;
736 task(std::future::poll_fn(move |_| {
737 let _ = &guard;
738 Poll::Pending
739 }));
740 let dropped = Rc::new(Cell::new(false));
741 let handle = task(pending_forever(dropped.clone()));
742 shutdown_tasks();
743 assert!(dropped.get());
744 assert!(handle.is_finished());
745 assert!(TASKS.with(|tasks| tasks.borrow().is_empty()));
746 }
747}