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 Dialog(Dialog, Rc<RefCell<Output<i32>>>),
75 CloseDialog(Rc<RefCell<Output<i32>>>),
78 Return(u32, super::JsResult),
80 ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
83 Fetch(
86 Box<crate::platform::HttpRequest>,
87 AnswerSlot<Result<super::services::HttpResponse, super::services::FetchFailure>>,
88 ),
89 ReadClipboard(ClipboardRead),
91 MainThread(crate::main_thread::MainThreadTask),
93 RegisterFont(Vec<u8>, AnswerSlot<Result<String, String>>),
96 PickImages(
99 crate::picker::PickRequest,
100 AnswerSlot<Vec<crate::picker::PickedFile>>,
101 ),
102 PickFiles(
105 crate::picker::FilePickRequest,
106 AnswerSlot<Vec<crate::picker::PickedFile>>,
107 ),
108 HostCall {
111 name: String,
112 args: crate::JsonValue,
113 answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
114 },
115 HostPost {
118 name: String,
119 args: crate::JsonValue,
120 },
121 ForgetHostCalls,
124 OpenUrl(String, AnswerSlot<bool>),
128 PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
131 Share(
134 crate::share::ShareRequest,
135 AnswerSlot<Result<crate::share::ShareOutcome, crate::share::ShareError>>,
136 ),
137 ShareAvailable(AnswerSlot<bool>),
140 AuthSession(
143 crate::auth_session::AuthSessionRequest,
144 AnswerSlot<
145 Result<crate::auth_session::AuthSessionOutcome, crate::auth_session::AuthSessionError>,
146 >,
147 ),
148 CloseAuthSession,
151 RenderCanvas(
155 Box<crate::canvas::render::RenderRequest>,
156 AnswerSlot<Result<Vec<u8>, super::JsError>>,
157 ),
158 Speech(SpeechAction),
160 Notification(NotificationAction),
162 LoginItem(
166 Option<bool>,
167 AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
168 ),
169 NextUrlSchemeOpen(AnswerSlot<String>),
172 NextOpenFiles(AnswerSlot<Vec<std::path::PathBuf>>),
176 NextSecondInstance(AnswerSlot<crate::single_instance::SecondInstance>),
180 NextAppUrlChange(AnswerSlot<crate::url_scheme::AppUrlChange>),
183 AppUrl(AnswerSlot<Option<String>>),
185 SetAppUrl(String, crate::url_scheme::HistoryBehavior),
188 Audio(AudioAction),
190 WebInputAvailable(AnswerSlot<bool>),
194 WebEvaluateAvailable(AnswerSlot<bool>),
196 WebViewAvailable(AnswerSlot<bool>),
199 DownloadDecision {
203 node: NodeId,
205 id: String,
207 decision: crate::webview::downloads::Decision,
209 answer: AnswerSlot<Result<(), String>>,
211 },
212 FileRequest(crate::file_dialog::FileRequest, FileAnswer),
215 Animation(crate::animation::AnimationOp),
217 Animate {
219 op: crate::animation::AnimationOp,
220 animation: crate::animation::AnimationId,
221 end: AnswerSlot<bool>,
222 },
223 ReadValue {
225 node: crate::animation::NodeId,
226 value: AnswerSlot<f32>,
227 },
228 ReportViewable(NodeId),
231 Hint(NodeId),
234 Frame(AnswerSlot<Instant>),
236 Appearance(crate::platform::Appearance),
238 Tokens(super::Tokens),
240 Translations(crate::i18n::Translations),
242 Locale(Option<crate::platform::Locale>),
245 BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
248 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
251 MeasureScrollPosition(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>),
255 Evaluate(
258 NodeId,
259 String,
260 std::time::Duration,
261 crate::platform::web_evaluation::Slot,
262 ),
263 WebEvaluationTimeout(u32),
265 CanvasRenderTimeout(u32),
267 TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
270 TextContent(NodeId, AnswerSlot<String>),
273 PressAt(NodeId, crate::PressEvent, AnswerSlot<bool>),
277 HoverAt(NodeId, Option<crate::MouseEvent>),
281}
282
283pub(crate) enum SpeechAction {
286 Start {
289 id: u32,
290 request: crate::speech::SpeechRequest,
291 sink: crate::speech::SpeechSink,
292 },
293 Stop(u32),
295 Abort(u32),
297 Available(AnswerSlot<bool>),
299}
300
301pub(crate) enum AudioAction {
303 Open {
307 command: crate::audio::AudioCommand,
308 sink: crate::audio::AudioSink,
309 },
310 Command(crate::audio::AudioCommand),
312 Available(AnswerSlot<bool>),
314}
315
316pub(crate) enum NotificationAction {
318 Permission {
321 ask: bool,
322 answer: AnswerSlot<crate::notifications::NotificationPermission>,
323 },
324 Show {
326 notification: crate::notifications::Notification,
327 answer: AnswerSlot<bool>,
328 },
329 Close(String),
331 CloseAll,
333 SetBadge(u32),
335 NextPress(AnswerSlot<String>),
337}
338
339pub(crate) enum FileAnswer {
342 OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
344 SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
346 Done(AnswerSlot<Result<(), String>>),
348 Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
350}
351
352impl FileAnswer {
353 pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
356 match self {
357 FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
358 Some(error) => Err(error),
359 None => Ok((!paths.is_empty()).then_some(paths)),
360 }),
361 FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
362 Some(error) => Err(error),
363 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
364 }),
365 FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
366 Some(error) => Err(error),
367 None => Ok(()),
368 }),
369 FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
370 Some(error) => Err(error),
371 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
372 }),
373 }
374 }
375}
376
377pub(crate) enum ClipboardRead {
379 Text(AnswerSlot<String>),
381 CheckedText(AnswerSlot<Option<String>>),
384 Has(AnswerSlot<bool>),
386 Image(AnswerSlot<Option<ClipboardImage>>),
389 CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
392 HasImage(AnswerSlot<bool>),
394 Files(AnswerSlot<Vec<String>>),
396}
397
398#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
404#[prop(exact)]
405#[non_exhaustive]
406pub struct ClipboardItem {
407 pub text: String,
409 #[prop(skip_none)]
411 pub html: Option<String>,
412}
413
414#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
416pub struct ClipboardImage {
417 pub url: String,
420 pub size: Size<DevicePixels>,
422}
423
424#[derive(Debug, Clone, Copy, Default, PartialEq)]
426pub struct ImageSize {
427 pub width: DevicePixels,
429 pub height: DevicePixels,
431}
432
433impl ImageSize {
434 pub fn size(&self) -> Size<DevicePixels> {
436 Size::new(self.width, self.height)
437 }
438}
439
440impl From<ImageSize> for Size<DevicePixels> {
441 fn from(s: ImageSize) -> Self {
442 s.size()
443 }
444}
445
446impl super::JsValue for ImageSize {
448 fn ts_type(types: &mut super::TsTypes) -> String {
449 <Size<DevicePixels> as super::JsValue>::ts_type(types)
450 }
451
452 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
453 if value.kind() != super::JsKind::Object {
454 return Err(value.expected("an object"));
455 }
456 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
457 let v = value.field(key)?;
458 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
459 };
460 Ok(ImageSize {
461 width: side("width")?,
462 height: side("height")?,
463 })
464 }
465
466 fn to_js<'a>(
467 &self,
468 host: &'a dyn super::JsHost,
469 ) -> Result<super::JsOwned<'a>, super::PropError> {
470 let owned = super::JsOwned::new(host, host.new_object()?);
471 let object = owned.get().raw();
472 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
473 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
474 Ok(owned)
475 }
476}
477
478pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
480 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
481}
482
483struct Entry {
484 host: NodeId,
485 future: Option<LocalFuture>,
487}
488
489#[derive(Default)]
490struct Inner {
491 tasks: FxHashMap<u64, Entry>,
492 next_task: u64,
493 actions: VecDeque<Action>,
494 failures: Vec<(NodeId, String)>,
495}
496
497#[derive(Default)]
499pub(crate) struct Executor {
500 inner: RefCell<Inner>,
501 ready: Arc<Ready>,
502 runtime: RefCell<Option<Handle>>,
504 animation_ids: std::cell::Cell<u32>,
507 derived: RefCell<super::animated::Derived>,
510 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
512 pub(crate) quit: Rc<RefCell<super::quit::QuitListeners>>,
514 pub(crate) quitting: Rc<std::cell::Cell<usize>>,
516 pub(crate) quit_requests: Rc<RefCell<super::quit::QuitRequestListeners>>,
518 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
520 pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
522 pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
524 timers: Arc<Timers>,
528 answers: RefCell<Answers>,
531 pub(crate) sounds: RefCell<super::audio::Sounds>,
533}
534
535#[derive(Default)]
537struct Answers {
538 waiting: Vec<AfterAnswer>,
540 due: Vec<AfterAnswer>,
543}
544
545pub(crate) struct AfterAnswer {
547 pub(crate) owner: super::Owner,
548 pub(crate) f: Box<dyn FnOnce()>,
549}
550
551#[derive(Default)]
556struct Timers(Mutex<TimerQueue>);
557
558#[derive(Default)]
559struct TimerQueue {
560 next_seq: u64,
561 wakers: BTreeMap<(Instant, u64), Waker>,
562}
563
564impl Timers {
565 fn queue(&self) -> std::sync::MutexGuard<'_, TimerQueue> {
566 self.0
567 .lock()
568 .unwrap_or_else(std::sync::PoisonError::into_inner)
569 }
570}
571
572#[derive(Debug)]
575pub(crate) struct TimerKey {
576 timers: std::sync::Weak<Timers>,
577 key: (Instant, u64),
578}
579
580impl TimerKey {
581 pub(crate) fn set_waker(&self, waker: &Waker) {
584 let Some(timers) = self.timers.upgrade() else {
585 return;
586 };
587 let old = {
588 let mut queue = timers.queue();
589 match queue.wakers.get_mut(&self.key) {
590 Some(kept) if !kept.will_wake(waker) => {
591 Some(std::mem::replace(kept, waker.clone()))
592 }
593 _ => None,
594 }
595 };
596 drop(old);
598 }
599}
600
601impl Drop for TimerKey {
602 fn drop(&mut self) {
603 let Some(timers) = self.timers.upgrade() else {
604 return;
605 };
606 let waker = timers.queue().wakers.remove(&self.key);
607 drop(waker);
608 }
609}
610
611impl Executor {
612 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
614 self.derived.borrow_mut()
615 }
616
617 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) -> TimerKey {
619 let mut queue = self.timers.queue();
620 let key = (at, queue.next_seq);
621 queue.next_seq += 1;
622 queue.wakers.insert(key, waker);
623 TimerKey {
624 timers: Arc::downgrade(&self.timers),
625 key,
626 }
627 }
628
629 pub(crate) fn next_timer(&self) -> Option<Instant> {
631 self.timers
632 .queue()
633 .wakers
634 .first_key_value()
635 .map(|(&(at, _), _)| at)
636 }
637
638 pub(crate) fn fire_timers(&self, now: Instant) {
640 let mut due = Vec::new();
641 {
642 let mut queue = self.timers.queue();
643 while let Some(timer) = queue.wakers.first_entry()
644 && timer.key().0 <= now
645 {
646 due.push(timer.remove());
647 }
648 }
649 for waker in due {
651 waker.wake();
652 }
653 }
654
655 pub(crate) fn next_animation_id(&self) -> u32 {
657 let n = self.animation_ids.get();
658 self.animation_ids.set(n + 1);
659 2 * n + 1
660 }
661
662 pub(crate) fn set_runtime(&self, runtime: Handle) {
663 *self.runtime.borrow_mut() = Some(runtime);
664 }
665
666 #[cfg(not(target_arch = "wasm32"))]
668 pub(crate) fn runtime(&self) -> Option<Handle> {
669 self.runtime.borrow().clone()
670 }
671
672 pub(crate) fn set_notify(&self, notify: Notify) {
673 *self.ready.notify.lock().expect("notify lock") = Some(notify);
674 }
675
676 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
677 let id = {
678 let mut inner = self.inner.borrow_mut();
679 inner.next_task += 1;
680 let id = inner.next_task;
681 inner.tasks.insert(
682 id,
683 Entry {
684 host,
685 future: Some(future),
686 },
687 );
688 id
689 };
690 self.ready.ids.lock().expect("ready lock").push(id);
692 let notify = self.ready.notify.lock().expect("notify lock").clone();
693 if let Some(notify) = notify {
694 notify();
695 }
696 id
697 }
698
699 fn cancel(&self, id: u64) {
700 let removed = self.inner.borrow_mut().tasks.remove(&id);
701 drop(removed);
703 }
704
705 pub(crate) fn poll_ready(&self) -> bool {
707 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
708 if ids.is_empty() {
709 return false;
710 }
711 ids.sort_unstable();
712 ids.dedup();
713 let runtime = self.runtime.borrow().clone();
715 let _context = runtime.as_ref().map(Handle::enter);
716 for id in ids {
717 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
718 Some(entry) => entry.future.take(),
719 None => None,
720 };
721 let Some(mut future) = future else { continue };
722 let waker = Waker::from(Arc::new(TaskWaker {
723 id,
724 ready: self.ready.clone(),
725 }));
726 let done = match super::component::caught(|| {
727 future
728 .as_mut()
729 .poll(&mut TaskContext::from_waker(&waker))
730 .is_ready()
731 }) {
732 Ok(done) => done,
733 Err(message) => {
735 let mut inner = self.inner.borrow_mut();
736 if let Some(entry) = inner.tasks.get(&id) {
737 let host = entry.host;
738 inner.failures.push((host, message));
739 }
740 true
741 }
742 };
743 if done {
744 self.inner.borrow_mut().tasks.remove(&id);
745 drop(future);
746 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
747 entry.future = Some(future);
748 }
749 }
750 true
751 }
752
753 #[cfg(test)]
754 pub(crate) fn task_count(&self) -> usize {
755 self.inner.borrow().tasks.len()
756 }
757
758 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
760 std::mem::take(&mut self.inner.borrow_mut().failures)
761 }
762
763 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
765 std::mem::take(&mut self.inner.borrow_mut().actions)
766 }
767
768 pub(crate) fn act(&self, action: Action) {
769 self.inner.borrow_mut().actions.push_back(action);
770 let notify = self.ready.notify.lock().expect("notify lock").clone();
771 if let Some(notify) = notify {
772 notify();
773 }
774 }
775
776 pub(crate) fn after_answer(&self, answer: AfterAnswer) {
779 self.answers.borrow_mut().waiting.push(answer);
780 }
781
782 pub(crate) fn hand_answers(&self) {
784 let mut answers = self.answers.borrow_mut();
785 let Answers { waiting, due } = &mut *answers;
786 if !waiting.is_empty() {
787 due.append(waiting);
788 }
789 }
790
791 pub(crate) fn has_due_answers(&self) -> bool {
793 !self.answers.borrow().due.is_empty()
794 }
795
796 #[cfg(test)]
798 pub(crate) fn answers_allocated(&self) -> bool {
799 let answers = self.answers.borrow();
800 answers.waiting.capacity() > 0 || answers.due.capacity() > 0
801 }
802
803 pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
805 std::mem::take(&mut self.answers.borrow_mut().due)
806 }
807}
808
809#[must_use = "a dropped task is cancelled: keep it, or detach it"]
813pub struct Task<T> {
814 executor: Weak<Executor>,
815 id: u64,
816 output: Rc<RefCell<Output<T>>>,
817 detached: bool,
818}
819
820pub(crate) struct Output<T> {
822 pub(crate) value: Option<T>,
823 pub(crate) waker: Option<Waker>,
824}
825
826pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
828
829impl<T> Default for Output<T> {
830 fn default() -> Self {
831 Self {
832 value: None,
833 waker: None,
834 }
835 }
836}
837
838impl<T> Output<T> {
839 pub(crate) fn deliver(&mut self, value: T) {
841 self.value = Some(value);
842 if let Some(waker) = self.waker.take() {
843 waker.wake();
844 }
845 }
846}
847
848#[must_use = "an answer does nothing unless awaited"]
851pub struct Answer<T> {
852 slot: Rc<RefCell<Output<T>>>,
853}
854
855pub type DialogAnswer = Answer<i32>;
858
859impl<T> Answer<T> {
860 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
861 let slot = Rc::new(RefCell::new(Output::default()));
862 (Self { slot: slot.clone() }, slot)
863 }
864}
865
866impl Answer<i32> {
867 pub fn closer(&self) -> DialogCloser {
870 DialogCloser {
871 slot: self.slot.clone(),
872 }
873 }
874}
875
876#[derive(Clone)]
880pub struct DialogCloser {
881 slot: Rc<RefCell<Output<i32>>>,
882}
883
884impl std::fmt::Debug for DialogCloser {
885 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
886 f.debug_struct("DialogCloser").finish_non_exhaustive()
887 }
888}
889
890impl DialogCloser {
891 pub fn close(&self) {
895 super::ambient::act_if_running(Action::CloseDialog(self.slot.clone()));
896 }
897}
898
899impl<T> std::fmt::Debug for Answer<T> {
900 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
901 f.debug_struct("Answer").finish_non_exhaustive()
902 }
903}
904
905impl<T> Future for Answer<T> {
906 type Output = T;
907
908 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
909 let mut slot = self.slot.borrow_mut();
910 match slot.value.take() {
911 Some(value) => Poll::Ready(value),
912 None => {
913 slot.waker = Some(cx.waker().clone());
914 Poll::Pending
915 }
916 }
917 }
918}
919
920impl<T> std::fmt::Debug for Task<T> {
921 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
922 f.debug_struct("Task")
923 .field("id", &self.id)
924 .finish_non_exhaustive()
925 }
926}
927
928impl<T> Task<T> {
929 pub fn detach(mut self) {
932 self.detached = true;
933 }
934}
935
936impl<T> Drop for Task<T> {
937 fn drop(&mut self) {
938 if !self.detached
939 && let Some(executor) = self.executor.upgrade()
940 {
941 executor.cancel(self.id);
942 }
943 }
944}
945
946impl<T> Future for Task<T> {
947 type Output = T;
948
949 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
950 let mut output = self.output.borrow_mut();
951 match output.value.take() {
952 Some(value) => Poll::Ready(value),
953 None => {
954 output.waker = Some(cx.waker().clone());
955 Poll::Pending
956 }
957 }
958 }
959}
960
961pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
963 executor.spawn(host, future)
964}
965
966pub(crate) fn act_after(
969 executor: &Rc<Executor>,
970 host: NodeId,
971 delay: Duration,
972 action: Action,
973) -> Task<()> {
974 let weak = Rc::downgrade(executor);
975 let acting = weak.clone();
976 let at = crate::time::now() + delay;
978 let id = executor.spawn(
979 host,
980 Box::pin(async move {
981 super::timer_until(at).await;
982 if let Some(executor) = acting.upgrade() {
983 executor.act(action);
984 }
985 }),
986 );
987 Task {
988 executor: weak,
989 id,
990 output: Rc::new(RefCell::new(Output::default())),
991 detached: false,
992 }
993}
994
995pub(crate) fn spawn_future<R: 'static>(
999 executor: &Rc<Executor>,
1000 future: impl Future<Output = R> + 'static,
1001) -> Task<R> {
1002 let weak = Rc::downgrade(executor);
1003 let output = Rc::new(RefCell::new(Output {
1004 value: None,
1005 waker: None,
1006 }));
1007 let done = output.clone();
1008 let id = executor.spawn(
1009 0,
1010 Box::pin(async move {
1011 let value = future.await;
1012 let mut output = done.borrow_mut();
1013 output.value = Some(value);
1014 if let Some(waker) = output.waker.take() {
1015 waker.wake();
1016 }
1017 }),
1018 );
1019 Task {
1020 executor: weak,
1021 id,
1022 output,
1023 detached: true,
1024 }
1025}
1026
1027pub(crate) struct TaskHandle {
1029 executor: Weak<Executor>,
1030 id: u64,
1031}
1032
1033impl TaskHandle {
1034 pub(crate) fn cancel(&self) {
1036 if let Some(executor) = self.executor.upgrade() {
1037 executor.cancel(self.id);
1038 }
1039 }
1040}
1041
1042impl<T> Task<T> {
1043 pub(crate) fn handle(&self) -> TaskHandle {
1045 TaskHandle {
1046 executor: self.executor.clone(),
1047 id: self.id,
1048 }
1049 }
1050}