1use std::{
13 cell::RefCell,
14 collections::{BTreeMap, VecDeque},
15 future::Future,
16 pin::Pin,
17 rc::{Rc, Weak},
18 sync::{Arc, Mutex},
19 task::{Context as TaskContext, Poll, Wake, Waker},
20 time::Duration,
21};
22
23use rustc_hash::FxHashMap;
24use tokio::runtime::Handle;
25
26use crate::{
27 Command, Dialog, NodeId, ROOT_ID, StatusBarSetting,
28 geometry::{DevicePixels, Size},
29 time::Instant,
30};
31
32type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
33
34pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
36
37#[derive(Default)]
39struct Ready {
40 ids: Mutex<Vec<u64>>,
41 notify: Mutex<Option<Notify>>,
42}
43
44struct TaskWaker {
45 id: u64,
46 ready: Arc<Ready>,
47}
48
49impl Wake for TaskWaker {
50 fn wake(self: Arc<Self>) {
51 self.wake_by_ref();
52 }
53
54 fn wake_by_ref(self: &Arc<Self>) {
55 self.ready.ids.lock().expect("ready lock").push(self.id);
56 let notify = self.ready.notify.lock().expect("notify lock").clone();
57 if let Some(notify) = notify {
58 notify();
59 }
60 }
61}
62
63pub(crate) enum Action {
65 Command(NodeId, Command),
66 FocusBack {
70 to: NodeId,
71 from: Option<NodeId>,
72 },
73 FocusOrigin {
77 to: NodeId,
78 },
79 Dialog(Dialog, Rc<RefCell<Output<DialogReply>>>),
81 CloseDialog(Rc<RefCell<Output<DialogReply>>>),
84 Return(u32, super::JsResult),
86 ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
89 Fetch(
92 Box<crate::platform::HttpRequest>,
93 AnswerSlot<Result<super::services::HttpResponse, super::services::FetchFailure>>,
94 ),
95 ReadClipboard(ClipboardRead),
97 MainThread(crate::main_thread::MainThreadTask),
99 RegisterFont(Vec<u8>, AnswerSlot<Result<String, String>>),
102 PickImages(
105 crate::picker::PickRequest,
106 AnswerSlot<Vec<crate::picker::PickedFile>>,
107 ),
108 PickFiles(
111 crate::picker::FilePickRequest,
112 AnswerSlot<Vec<crate::picker::PickedFile>>,
113 ),
114 HostCall {
117 name: String,
118 args: crate::JsonValue,
119 answer: AnswerSlot<Result<crate::JsonValue, crate::host_channel::HostError>>,
120 },
121 HostPost {
124 name: String,
125 args: crate::JsonValue,
126 },
127 ForgetHostCalls,
130 OpenUrl(String, AnswerSlot<bool>),
134 OpenAppSettings(AnswerSlot<Result<bool, crate::mobile::AppSettingsError>>),
138 AppSettingsAvailable(AnswerSlot<bool>),
141 WriteClipboard(crate::Command, AnswerSlot<ClipboardWrite>),
146 PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
149 Share(
152 crate::share::ShareRequest,
153 AnswerSlot<Result<crate::share::ShareOutcome, crate::share::ShareError>>,
154 ),
155 ShareAvailable(AnswerSlot<bool>),
158 AuthSession(
161 crate::auth_session::AuthSessionRequest,
162 AnswerSlot<
163 Result<crate::auth_session::AuthSessionOutcome, crate::auth_session::AuthSessionError>,
164 >,
165 ),
166 CloseAuthSession,
169 RenderCanvas(
173 Box<crate::canvas::render::RenderRequest>,
174 AnswerSlot<Result<Vec<u8>, super::JsError>>,
175 ),
176 Notification(NotificationAction),
178 LoginItem(
182 Option<bool>,
183 AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
184 ),
185 NextUrlSchemeOpen(AnswerSlot<String>),
188 NextOpenFiles(AnswerSlot<Vec<std::path::PathBuf>>),
192 NextSecondInstance(AnswerSlot<crate::single_instance::SecondInstance>),
196 NextAppUrlChange(AnswerSlot<crate::url_scheme::AppUrlChange>),
199 AppUrl(AnswerSlot<Option<String>>),
201 SetAppUrl(String, crate::url_scheme::HistoryBehavior),
204 Audio(AudioAction),
206 WebInputAvailable(AnswerSlot<bool>),
210 WebEvaluateAvailable(AnswerSlot<bool>),
212 WebViewAvailable(AnswerSlot<bool>),
215 DownloadDecision {
219 node: NodeId,
221 id: String,
223 decision: crate::webview::downloads::Decision,
225 answer: AnswerSlot<Result<(), String>>,
227 },
228 FileRequest(crate::file_dialog::FileRequest, FileAnswer),
231 Animation(crate::animation::AnimationOp),
233 Animate {
235 op: crate::animation::AnimationOp,
236 animation: crate::animation::AnimationId,
237 end: AnswerSlot<bool>,
238 },
239 ReadValue {
241 node: crate::animation::NodeId,
242 value: AnswerSlot<f32>,
243 },
244 ReportViewable(NodeId),
247 Hint(NodeId),
250 Frame(AnswerSlot<Instant>),
252 Appearance(crate::platform::Appearance),
254 Tokens(super::Tokens),
256 Translations(crate::i18n::Translations),
258 AddTranslations(std::collections::HashMap<String, std::collections::HashMap<String, String>>),
260 TranslationsChanged(crate::i18n::Translations),
263 Locale(Option<crate::platform::Locale>),
266 BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
269 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
272 MeasureScrollPosition(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>),
276 Evaluate(
279 NodeId,
280 String,
281 std::time::Duration,
282 crate::platform::web_evaluation::Slot,
283 ),
284 WebEvaluationTimeout(u32),
286 CanvasRenderTimeout(u32),
288 TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
291 TextContent(NodeId, AnswerSlot<String>),
294 PressAt(NodeId, crate::PressEvent, AnswerSlot<bool>),
298 HoverAt(NodeId, Option<crate::MouseEvent>),
302}
303
304pub(crate) enum AudioAction {
306 Open {
310 command: crate::audio::AudioCommand,
311 sink: crate::audio::AudioSink,
312 },
313 Command(crate::audio::AudioCommand),
315 Available(AnswerSlot<bool>),
317}
318
319pub(crate) enum NotificationAction {
321 Permission {
324 ask: bool,
325 answer: AnswerSlot<crate::notifications::NotificationPermission>,
326 },
327 Show {
329 notification: crate::notifications::Notification,
330 answer: AnswerSlot<bool>,
331 },
332 Close(String),
334 CloseAll,
336 SetBadge(u32),
338 NextPress(AnswerSlot<String>),
340}
341
342pub(crate) enum FileAnswer {
345 OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
347 SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
349 Done(AnswerSlot<Result<(), String>>),
351 Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
353}
354
355impl FileAnswer {
356 pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
359 match self {
360 FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
361 Some(error) => Err(error),
362 None => Ok((!paths.is_empty()).then_some(paths)),
363 }),
364 FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
365 Some(error) => Err(error),
366 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
367 }),
368 FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
369 Some(error) => Err(error),
370 None => Ok(()),
371 }),
372 FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
373 Some(error) => Err(error),
374 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
375 }),
376 }
377 }
378}
379
380pub(crate) enum ClipboardRead {
382 Text(AnswerSlot<String>),
384 CheckedText(AnswerSlot<Option<String>>),
387 Has(AnswerSlot<bool>),
389 Image(AnswerSlot<Option<ClipboardImage>>),
392 CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
395 HasImage(AnswerSlot<bool>),
397 Files(AnswerSlot<Vec<String>>),
399}
400
401#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
407#[prop(exact)]
408#[non_exhaustive]
409pub struct ClipboardItem {
410 pub text: String,
412 #[prop(skip_none)]
414 pub html: Option<String>,
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
422pub enum ClipboardWrite {
423 Written,
425 Failed,
428 #[default]
431 Requested,
432}
433
434#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
436pub struct ClipboardImage {
437 pub url: String,
440 pub size: Size<DevicePixels>,
442}
443
444#[derive(Debug, Clone, Copy, Default, PartialEq)]
446pub struct ImageSize {
447 pub width: DevicePixels,
449 pub height: DevicePixels,
451}
452
453impl ImageSize {
454 pub fn size(&self) -> Size<DevicePixels> {
456 Size::new(self.width, self.height)
457 }
458}
459
460impl From<ImageSize> for Size<DevicePixels> {
461 fn from(s: ImageSize) -> Self {
462 s.size()
463 }
464}
465
466impl super::JsValue for ImageSize {
468 fn ts_type(types: &mut super::TsTypes) -> String {
469 <Size<DevicePixels> as super::JsValue>::ts_type(types)
470 }
471
472 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
473 if value.kind() != super::JsKind::Object {
474 return Err(value.expected("an object"));
475 }
476 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
477 let v = value.field(key)?;
478 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
479 };
480 Ok(ImageSize {
481 width: side("width")?,
482 height: side("height")?,
483 })
484 }
485
486 fn to_js<'a>(
487 &self,
488 host: &'a dyn super::JsHost,
489 ) -> Result<super::JsOwned<'a>, super::PropError> {
490 let owned = super::JsOwned::new(host, host.new_object()?);
491 let object = owned.get().raw();
492 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
493 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
494 Ok(owned)
495 }
496}
497
498pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
500 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
501}
502
503struct Entry {
504 host: NodeId,
505 future: Option<LocalFuture>,
507}
508
509#[derive(Default)]
510struct Inner {
511 tasks: FxHashMap<u64, Entry>,
512 next_task: u64,
513 actions: VecDeque<Action>,
514 failures: Vec<(NodeId, String)>,
515}
516
517#[derive(Default)]
519pub(crate) struct Executor {
520 inner: RefCell<Inner>,
521 ready: Arc<Ready>,
522 runtime: RefCell<Option<Handle>>,
524 animation_ids: std::cell::Cell<u32>,
527 derived: RefCell<super::animated::Derived>,
530 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
532 pub(crate) back_progress: Rc<RefCell<super::back::BackProgressListeners>>,
534 pub(crate) host_events: Rc<RefCell<super::host_events::HostListeners>>,
537 pub(crate) quit: Rc<RefCell<super::quit::QuitListeners>>,
539 pub(crate) quitting: Rc<std::cell::Cell<usize>>,
541 pub(crate) quit_requests: Rc<RefCell<super::quit::QuitRequestListeners>>,
543 pub(crate) reopens: Rc<RefCell<super::quit::ReopenListeners>>,
546 pub(crate) last_window_closed: Rc<RefCell<super::quit::LastWindowClosedListeners>>,
549 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
551 pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
553 pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
555 timers: Arc<Timers>,
559 answers: RefCell<Answers>,
562 rendered: RefCell<Vec<AfterAnswer>>,
565 pub(crate) sounds: RefCell<super::audio::Sounds>,
567}
568
569#[derive(Default)]
571struct Answers {
572 waiting: Vec<AfterAnswer>,
574 due: Vec<AfterAnswer>,
577}
578
579pub(crate) struct AfterAnswer {
582 pub(crate) owner: super::Owner,
583 pub(crate) f: Box<dyn FnOnce()>,
584}
585
586#[derive(Default)]
591struct Timers(Mutex<TimerQueue>);
592
593#[derive(Default)]
594struct TimerQueue {
595 next_seq: u64,
596 wakers: BTreeMap<(Instant, u64), Waker>,
597}
598
599impl Timers {
600 fn queue(&self) -> std::sync::MutexGuard<'_, TimerQueue> {
601 self.0
602 .lock()
603 .unwrap_or_else(std::sync::PoisonError::into_inner)
604 }
605}
606
607#[derive(Debug)]
610pub(crate) struct TimerKey {
611 timers: std::sync::Weak<Timers>,
612 key: (Instant, u64),
613}
614
615impl TimerKey {
616 pub(crate) fn set_waker(&self, waker: &Waker) {
619 let Some(timers) = self.timers.upgrade() else {
620 return;
621 };
622 let old = {
623 let mut queue = timers.queue();
624 match queue.wakers.get_mut(&self.key) {
625 Some(kept) if !kept.will_wake(waker) => {
626 Some(std::mem::replace(kept, waker.clone()))
627 }
628 _ => None,
629 }
630 };
631 drop(old);
633 }
634}
635
636impl Drop for TimerKey {
637 fn drop(&mut self) {
638 let Some(timers) = self.timers.upgrade() else {
639 return;
640 };
641 let waker = timers.queue().wakers.remove(&self.key);
642 drop(waker);
643 }
644}
645
646impl Executor {
647 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
649 self.derived.borrow_mut()
650 }
651
652 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) -> TimerKey {
654 let mut queue = self.timers.queue();
655 let key = (at, queue.next_seq);
656 queue.next_seq += 1;
657 queue.wakers.insert(key, waker);
658 TimerKey {
659 timers: Arc::downgrade(&self.timers),
660 key,
661 }
662 }
663
664 pub(crate) fn next_timer(&self) -> Option<Instant> {
666 self.timers
667 .queue()
668 .wakers
669 .first_key_value()
670 .map(|(&(at, _), _)| at)
671 }
672
673 pub(crate) fn fire_timers(&self, now: Instant) {
675 let mut due = Vec::new();
676 {
677 let mut queue = self.timers.queue();
678 while let Some(timer) = queue.wakers.first_entry()
679 && timer.key().0 <= now
680 {
681 due.push(timer.remove());
682 }
683 }
684 for waker in due {
686 waker.wake();
687 }
688 }
689
690 pub(crate) fn next_animation_id(&self) -> u32 {
692 let n = self.animation_ids.get();
693 self.animation_ids.set(n + 1);
694 2 * n + 1
695 }
696
697 pub(crate) fn set_runtime(&self, runtime: Handle) {
698 *self.runtime.borrow_mut() = Some(runtime);
699 }
700
701 #[cfg(not(target_arch = "wasm32"))]
703 pub(crate) fn runtime(&self) -> Option<Handle> {
704 self.runtime.borrow().clone()
705 }
706
707 pub(crate) fn set_notify(&self, notify: Notify) {
708 *self.ready.notify.lock().expect("notify lock") = Some(notify);
709 }
710
711 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
712 let id = {
713 let mut inner = self.inner.borrow_mut();
714 inner.next_task += 1;
715 let id = inner.next_task;
716 inner.tasks.insert(
717 id,
718 Entry {
719 host,
720 future: Some(future),
721 },
722 );
723 id
724 };
725 self.ready.ids.lock().expect("ready lock").push(id);
727 let notify = self.ready.notify.lock().expect("notify lock").clone();
728 if let Some(notify) = notify {
729 notify();
730 }
731 id
732 }
733
734 fn cancel(&self, id: u64) {
735 let removed = self.inner.borrow_mut().tasks.remove(&id);
736 drop(removed);
738 }
739
740 pub(crate) fn poll_ready(&self) -> bool {
742 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
743 if ids.is_empty() {
744 return false;
745 }
746 ids.sort_unstable();
747 ids.dedup();
748 let runtime = self.runtime.borrow().clone();
750 let _context = runtime.as_ref().map(Handle::enter);
751 for id in ids {
752 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
753 Some(entry) => entry.future.take(),
754 None => None,
755 };
756 let Some(mut future) = future else { continue };
757 let waker = Waker::from(Arc::new(TaskWaker {
758 id,
759 ready: self.ready.clone(),
760 }));
761 let done = match super::component::caught(|| {
762 future
763 .as_mut()
764 .poll(&mut TaskContext::from_waker(&waker))
765 .is_ready()
766 }) {
767 Ok(done) => done,
768 Err(message) => {
770 let mut inner = self.inner.borrow_mut();
771 if let Some(entry) = inner.tasks.get(&id) {
772 let host = entry.host;
773 inner.failures.push((host, message));
774 }
775 true
776 }
777 };
778 if done {
779 self.inner.borrow_mut().tasks.remove(&id);
780 drop(future);
781 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
782 entry.future = Some(future);
783 }
784 }
785 true
786 }
787
788 #[cfg(test)]
789 pub(crate) fn task_count(&self) -> usize {
790 self.inner.borrow().tasks.len()
791 }
792
793 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
795 std::mem::take(&mut self.inner.borrow_mut().failures)
796 }
797
798 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
800 std::mem::take(&mut self.inner.borrow_mut().actions)
801 }
802
803 pub(crate) fn act(&self, action: Action) {
804 self.inner.borrow_mut().actions.push_back(action);
805 let notify = self.ready.notify.lock().expect("notify lock").clone();
806 if let Some(notify) = notify {
807 notify();
808 }
809 }
810
811 pub(crate) fn after_answer(&self, answer: AfterAnswer) {
814 self.answers.borrow_mut().waiting.push(answer);
815 }
816
817 pub(crate) fn hand_answers(&self) {
819 let mut answers = self.answers.borrow_mut();
820 let Answers { waiting, due } = &mut *answers;
821 if !waiting.is_empty() {
822 due.append(waiting);
823 }
824 }
825
826 pub(crate) fn has_due_answers(&self) -> bool {
828 !self.answers.borrow().due.is_empty()
829 }
830
831 #[cfg(test)]
833 pub(crate) fn answers_allocated(&self) -> bool {
834 let answers = self.answers.borrow();
835 answers.waiting.capacity() > 0 || answers.due.capacity() > 0
836 }
837
838 pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
840 std::mem::take(&mut self.answers.borrow_mut().due)
841 }
842
843 pub(crate) fn after_render(&self, f: AfterAnswer) {
846 self.rendered.borrow_mut().push(f);
847 }
848
849 pub(crate) fn take_rendered(&self) -> Vec<AfterAnswer> {
851 std::mem::take(&mut self.rendered.borrow_mut())
852 }
853}
854
855#[must_use = "a dropped task is cancelled: keep it, or detach it"]
859pub struct Task<T> {
860 executor: Weak<Executor>,
861 id: u64,
862 output: Rc<RefCell<Output<T>>>,
863 detached: bool,
864}
865
866pub(crate) struct Output<T> {
868 pub(crate) value: Option<T>,
869 pub(crate) waker: Option<Waker>,
870}
871
872pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
874
875impl<T> Default for Output<T> {
876 fn default() -> Self {
877 Self {
878 value: None,
879 waker: None,
880 }
881 }
882}
883
884impl<T> Output<T> {
885 pub(crate) fn deliver(&mut self, value: T) {
887 self.value = Some(value);
888 if let Some(waker) = self.waker.take() {
889 waker.wake();
890 }
891 }
892}
893
894#[must_use = "an answer does nothing unless awaited"]
897pub struct Answer<T> {
898 slot: Rc<RefCell<Output<T>>>,
899}
900
901pub type DialogAnswer = Answer<DialogReply>;
904
905#[derive(Debug, Clone, Default, PartialEq, Eq)]
907#[non_exhaustive]
908pub struct DialogReply {
909 pub index: i32,
911 pub value: Option<String>,
915}
916
917impl DialogReply {
918 pub fn dismissed() -> Self {
920 Self {
921 index: -1,
922 value: None,
923 }
924 }
925}
926
927impl<T> Answer<T> {
928 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
929 let slot = Rc::new(RefCell::new(Output::default()));
930 (Self { slot: slot.clone() }, slot)
931 }
932}
933
934impl Answer<DialogReply> {
935 pub fn closer(&self) -> DialogCloser {
938 DialogCloser {
939 slot: self.slot.clone(),
940 }
941 }
942}
943
944#[derive(Clone)]
948pub struct DialogCloser {
949 slot: Rc<RefCell<Output<DialogReply>>>,
950}
951
952impl std::fmt::Debug for DialogCloser {
953 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
954 f.debug_struct("DialogCloser").finish_non_exhaustive()
955 }
956}
957
958impl DialogCloser {
959 pub fn close(&self) {
963 super::ambient::act_if_running(Action::CloseDialog(self.slot.clone()));
964 }
965}
966
967impl<T> std::fmt::Debug for Answer<T> {
968 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969 f.debug_struct("Answer").finish_non_exhaustive()
970 }
971}
972
973impl<T> Future for Answer<T> {
974 type Output = T;
975
976 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
977 let mut slot = self.slot.borrow_mut();
978 match slot.value.take() {
979 Some(value) => Poll::Ready(value),
980 None => {
981 slot.waker = Some(cx.waker().clone());
982 Poll::Pending
983 }
984 }
985 }
986}
987
988impl<T> std::fmt::Debug for Task<T> {
989 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
990 f.debug_struct("Task")
991 .field("id", &self.id)
992 .finish_non_exhaustive()
993 }
994}
995
996impl<T> Task<T> {
997 pub fn detach(mut self) {
1000 self.detached = true;
1001 }
1002}
1003
1004impl<T> Drop for Task<T> {
1005 fn drop(&mut self) {
1006 if !self.detached
1007 && let Some(executor) = self.executor.upgrade()
1008 {
1009 executor.cancel(self.id);
1010 }
1011 }
1012}
1013
1014impl<T> Future for Task<T> {
1015 type Output = T;
1016
1017 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
1018 let mut output = self.output.borrow_mut();
1019 match output.value.take() {
1020 Some(value) => Poll::Ready(value),
1021 None => {
1022 output.waker = Some(cx.waker().clone());
1023 Poll::Pending
1024 }
1025 }
1026 }
1027}
1028
1029pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
1031 executor.spawn(host, future)
1032}
1033
1034pub(crate) fn act_after(
1037 executor: &Rc<Executor>,
1038 host: NodeId,
1039 delay: Duration,
1040 action: Action,
1041) -> Task<()> {
1042 let weak = Rc::downgrade(executor);
1043 let acting = weak.clone();
1044 let at = crate::time::now() + delay;
1046 let id = executor.spawn(
1047 host,
1048 Box::pin(async move {
1049 super::timer_until(at).await;
1050 if let Some(executor) = acting.upgrade() {
1051 executor.act(action);
1052 }
1053 }),
1054 );
1055 Task {
1056 executor: weak,
1057 id,
1058 output: Rc::new(RefCell::new(Output::default())),
1059 detached: false,
1060 }
1061}
1062
1063pub(crate) fn spawn_future<R: 'static>(
1067 executor: &Rc<Executor>,
1068 future: impl Future<Output = R> + 'static,
1069) -> Task<R> {
1070 let weak = Rc::downgrade(executor);
1071 let output = Rc::new(RefCell::new(Output {
1072 value: None,
1073 waker: None,
1074 }));
1075 let done = output.clone();
1076 let id = executor.spawn(
1077 0,
1078 Box::pin(async move {
1079 let value = future.await;
1080 let mut output = done.borrow_mut();
1081 output.value = Some(value);
1082 if let Some(waker) = output.waker.take() {
1083 waker.wake();
1084 }
1085 }),
1086 );
1087 Task {
1088 executor: weak,
1089 id,
1090 output,
1091 detached: true,
1092 }
1093}
1094
1095pub(crate) struct TaskHandle {
1097 executor: Weak<Executor>,
1098 id: u64,
1099}
1100
1101impl TaskHandle {
1102 pub(crate) fn cancel(&self) {
1104 if let Some(executor) = self.executor.upgrade() {
1105 executor.cancel(self.id);
1106 }
1107 }
1108}
1109
1110impl<T> Task<T> {
1111 pub(crate) fn handle(&self) -> TaskHandle {
1113 TaskHandle {
1114 executor: self.executor.clone(),
1115 id: self.id,
1116 }
1117 }
1118}