Skip to main content

nsh_core/element/
task.rs

1//! Async tasks ([`super::spawn`]): futures run on the engine thread (they
2//! may hold signals and other `!Send` handles) by a small executor of the
3//! core, polled inside a tokio runtime's context, so the tokio ecosystem
4//! works in them: network and file IO, channels; `Send` work goes to the
5//! runtime's threads ([`super::background`]). Their timers
6//! ([`super::timer`]) are the executor's own: the core fires them as they
7//! come due and the engine's loop wakes for the soonest, as for JS's.
8//! Wakers may fire on any thread: they wake the engine. A task changes
9//! what it wants by writing signals; it ends with the owner it was made
10//! under.
11
12use std::{
13    cell::RefCell,
14    cmp::Reverse,
15    collections::{BinaryHeap, VecDeque},
16    future::Future,
17    pin::Pin,
18    rc::{Rc, Weak},
19    sync::{Arc, Mutex},
20    task::{Context as TaskContext, Poll, Wake, Waker},
21    time::Duration,
22};
23
24use rustc_hash::FxHashMap;
25use tokio::runtime::Handle;
26
27use crate::{
28    Command, Dialog, NodeId, ROOT_ID, StatusBarSetting,
29    geometry::{DevicePixels, Size},
30    time::Instant,
31};
32
33type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
34
35/// Called when a task is woken (from any thread): the engine wakes up.
36pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
37
38/// Tasks woken since the last run.
39#[derive(Default)]
40struct Ready {
41    ids: Mutex<Vec<u64>>,
42    notify: Mutex<Option<Notify>>,
43}
44
45struct TaskWaker {
46    id: u64,
47    ready: Arc<Ready>,
48}
49
50impl Wake for TaskWaker {
51    fn wake(self: Arc<Self>) {
52        self.wake_by_ref();
53    }
54
55    fn wake_by_ref(self: &Arc<Self>) {
56        self.ready.ids.lock().expect("ready lock").push(self.id);
57        let notify = self.ready.notify.lock().expect("notify lock").clone();
58        if let Some(notify) = notify {
59            notify();
60        }
61    }
62}
63
64/// What a component or a task asks of the platform, applied by the core.
65pub(crate) enum Action {
66    Command(NodeId, Command),
67    /// A dialog; its answer resolves the slot.
68    Dialog(Dialog, Rc<RefCell<Output<i32>>>),
69    /// The result of a module function JS waits for.
70    Return(u32, super::JsResult),
71    /// The pixel size of the image at the URI (its bytes stay loaded); the
72    /// answer resolves the slot.
73    ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
74    /// An HTTP request for the engine's network stack; the response (or
75    /// its failure) resolves the slot.
76    Fetch(
77        Box<crate::platform::HttpRequest>,
78        AnswerSlot<Result<super::services::HttpResponse, String>>,
79    ),
80    /// Reads the system clipboard; the answer resolves the slot.
81    ReadClipboard(ClipboardRead),
82    /// Shows the system's picker for images; the files picked (none when
83    /// cancelled) resolve the slot.
84    PickImages(
85        crate::picker::PickRequest,
86        AnswerSlot<Vec<crate::picker::PickedFile>>,
87    ),
88    /// Calls function `name` of the embedding app (`nsh/host`); its
89    /// value, or why it failed, resolves the slot.
90    HostCall {
91        name: String,
92        args: crate::JsonValue,
93        answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
94    },
95    /// Drops the slots of the host calls whose answers are gone (they
96    /// timed out).
97    ForgetHostCalls,
98    /// Opens a URL outside the app (checked by
99    /// [`crate::open_url::check_url`]); whether it opened resolves the
100    /// slot.
101    OpenUrl(String, AnswerSlot<bool>),
102    /// Lets the user pick a color on the screen; the color (none when
103    /// cancelled or not supported) resolves the slot.
104    PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
105    /// A speech recognition session's request ([`crate::speech`]).
106    Speech(SpeechAction),
107    /// Whether a web view's ref gives its page trusted input here
108    /// (`sendInput`): the platform delivers it and the app holds
109    /// `webview.input`; the answer resolves the slot.
110    WebInputAvailable(AnswerSlot<bool>),
111    /// A request on local paths for the platform
112    /// ([`crate::file_dialog`]); its answer resolves the slot.
113    FileRequest(crate::file_dialog::FileRequest, FileAnswer),
114    /// An operation on the native animation graph.
115    Animation(crate::animation::AnimationOp),
116    /// Starts an animation; its end resolves the slot.
117    Animate {
118        op: crate::animation::AnimationOp,
119        animation: crate::animation::AnimationId,
120        end: AnswerSlot<bool>,
121    },
122    /// Reads a node's value where it moves; the value resolves the slot.
123    ReadValue {
124        node: crate::animation::NodeId,
125        value: AnswerSlot<f32>,
126    },
127    /// A component's own list reports the rows viewable now (they stayed
128    /// so for its minimum view time).
129    ReportViewable(NodeId),
130    /// A hint overlay's delay is over with the pointer on its anchor: it
131    /// shows.
132    Hint(NodeId),
133    /// The start of the next display frame resolves the slot.
134    Frame(AnswerSlot<Instant>),
135    /// Sets the app's appearance.
136    Appearance(crate::platform::Appearance),
137    /// Sets the app's design tokens.
138    Tokens(super::Tokens),
139    /// Draws the scroll views' bars with the built-in bar the source makes
140    /// of the theme, or (no theme) with the platform's indicator.
141    BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
142    /// Measures the node with the layout of the commit the action goes out
143    /// with; the measurement resolves the slot.
144    Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
145    /// How long the node's transitions run with the styles of the commit
146    /// the action goes out with; the time resolves the slot.
147    TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
148}
149
150/// What a speech recognition session asks of the core
151/// ([`Action::Speech`]).
152pub(crate) enum SpeechAction {
153    /// Starts session `id`, reporting to `sink`; the session running is
154    /// aborted first.
155    Start {
156        id: u32,
157        request: crate::speech::SpeechRequest,
158        sink: crate::speech::SpeechSink,
159    },
160    /// Stops session `id`: it finishes what it heard, then ends.
161    Stop(u32),
162    /// Ends session `id` at once, without an error.
163    Abort(u32),
164    /// Whether speech can be recognized; the answer resolves the slot.
165    Available(AnswerSlot<bool>),
166}
167
168/// A request on local paths waiting for the platform's answer
169/// ([`Action::FileRequest`]).
170pub(crate) enum FileAnswer {
171    /// The paths picked in the open dialog, none when cancelled.
172    OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
173    /// The path chosen in the save dialog, none when cancelled.
174    SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
175    /// The path opened or showed in the file manager, or why not.
176    Done(AnswerSlot<Result<(), String>>),
177    /// Where the trashed item went, or why it was not.
178    Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
179}
180
181impl FileAnswer {
182    /// Answers with the platform's `paths` (none: cancelled), or its
183    /// `error`.
184    pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
185        match self {
186            FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
187                Some(error) => Err(error),
188                None => Ok((!paths.is_empty()).then_some(paths)),
189            }),
190            FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
191                Some(error) => Err(error),
192                None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
193            }),
194            FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
195                Some(error) => Err(error),
196                None => Ok(()),
197            }),
198            FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
199                Some(error) => Err(error),
200                None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
201            }),
202        }
203    }
204}
205
206/// A clipboard read waiting for the platform's answer.
207pub(crate) enum ClipboardRead {
208    /// The text (`""` when it holds none).
209    Text(AnswerSlot<String>),
210    /// Whether it holds text.
211    Has(AnswerSlot<bool>),
212    /// The image (`None` when it holds none, or one over
213    /// [`crate::platform::clipboard::MAX_IMAGE_BYTES`]).
214    Image(AnswerSlot<Option<ClipboardImage>>),
215    /// The image for `Clipboard.readImage`: `Err` with the size in encoded
216    /// bytes of one over [`crate::platform::clipboard::MAX_IMAGE_BYTES`].
217    CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
218    /// Whether it holds an image.
219    HasImage(AnswerSlot<bool>),
220    /// The `file:` URLs of the local files on it.
221    Files(AnswerSlot<Vec<String>>),
222}
223
224/// An image read from the system clipboard (`Clipboard.readImage`).
225#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
226pub struct ClipboardImage {
227    /// A URL of the image that an `Image` shows (its `src`) and `fetch`
228    /// reads the bytes of; `Clipboard.writeImage` takes it back.
229    pub url: String,
230    /// Its size in pixels, as decoded.
231    pub size: Size<DevicePixels>,
232}
233
234/// An image's size in pixels (`Image.getSize`); TS: `PixelSize`.
235#[derive(Debug, Clone, Copy, Default, PartialEq)]
236pub struct ImageSize {
237    /// Width.
238    pub width: DevicePixels,
239    /// Height.
240    pub height: DevicePixels,
241}
242
243impl ImageSize {
244    /// As a [`Size`].
245    pub fn size(&self) -> Size<DevicePixels> {
246        Size::new(self.width, self.height)
247    }
248}
249
250impl From<ImageSize> for Size<DevicePixels> {
251    fn from(s: ImageSize) -> Self {
252        s.size()
253    }
254}
255
256/// TS: `PixelSize` (`{ width, height }`).
257impl super::JsValue for ImageSize {
258    fn ts_type(types: &mut super::TsTypes) -> String {
259        <Size<DevicePixels> as super::JsValue>::ts_type(types)
260    }
261
262    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
263        if value.kind() != super::JsKind::Object {
264            return Err(value.expected("an object"));
265        }
266        let side = |key: &str| -> Result<DevicePixels, super::PropError> {
267            let v = value.field(key)?;
268            DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
269        };
270        Ok(ImageSize {
271            width: side("width")?,
272            height: side("height")?,
273        })
274    }
275
276    fn to_js<'a>(
277        &self,
278        host: &'a dyn super::JsHost,
279    ) -> Result<super::JsOwned<'a>, super::PropError> {
280        let owned = super::JsOwned::new(host, host.new_object()?);
281        let object = owned.get().raw();
282        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
283        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
284        Ok(owned)
285    }
286}
287
288/// The status bar's base setting, as a command for the surface's root.
289pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
290    Action::Command(ROOT_ID, Command::SetStatusBar(patch))
291}
292
293struct Entry {
294    host: NodeId,
295    /// Out while it is polled.
296    future: Option<LocalFuture>,
297}
298
299#[derive(Default)]
300struct Inner {
301    tasks: FxHashMap<u64, Entry>,
302    next_task: u64,
303    actions: VecDeque<Action>,
304    failures: Vec<(NodeId, String)>,
305}
306
307/// The executor of one core's component tasks.
308#[derive(Default)]
309pub(crate) struct Executor {
310    inner: RefCell<Inner>,
311    ready: Arc<Ready>,
312    /// The runtime tasks are polled in the context of.
313    runtime: RefCell<Option<Handle>>,
314    /// Native animation nodes and animations made so far (their ids are
315    /// odd: JS's are even).
316    animation_ids: std::cell::Cell<u32>,
317    /// Live derived nodes, for what derives them again (a region or a row
318    /// made again).
319    derived: RefCell<super::animated::Derived>,
320    /// The components' listeners of the back button.
321    pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
322    /// The views' keyboard shortcuts.
323    pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
324    /// The views' menus' handlers.
325    pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
326    /// The views' watches of nodes they did not make.
327    pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
328    /// The timers tasks wait for ([`super::timer`]), soonest first: the core
329    /// fires them as they come due, and the engine's loop wakes for the
330    /// soonest, as it does for JS's timers.
331    timers: RefCell<BinaryHeap<Reverse<Timer>>>,
332    next_timer_seq: std::cell::Cell<u64>,
333    /// What waits for the app to answer the events emitted before it
334    /// ([`super::after_answer`]).
335    answers: RefCell<Answers>,
336}
337
338/// The closures of [`super::after_answer`], by how far their events went.
339#[derive(Default)]
340struct Answers {
341    /// Their events have not been handed to JS yet.
342    waiting: Vec<AfterAnswer>,
343    /// Their events went to JS: they run in the next commit, by when JS has
344    /// handled them and its ops are applied.
345    due: Vec<AfterAnswer>,
346}
347
348/// A closure of [`super::after_answer`] and the owner it runs under.
349pub(crate) struct AfterAnswer {
350    pub(crate) owner: super::Owner,
351    pub(crate) f: Box<dyn FnOnce()>,
352}
353
354/// A task's timer: when, and whom to wake (in the order they were made
355/// among timers due at once).
356struct Timer {
357    at: Instant,
358    seq: u64,
359    waker: Waker,
360}
361
362impl PartialEq for Timer {
363    fn eq(&self, other: &Self) -> bool {
364        (self.at, self.seq) == (other.at, other.seq)
365    }
366}
367
368impl Eq for Timer {}
369
370impl PartialOrd for Timer {
371    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
372        Some(self.cmp(other))
373    }
374}
375
376impl Ord for Timer {
377    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
378        (self.at, self.seq).cmp(&(other.at, other.seq))
379    }
380}
381
382impl Executor {
383    /// The derived nodes and their handles.
384    pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
385        self.derived.borrow_mut()
386    }
387
388    /// Wakes `waker` at `at`.
389    pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
390        let seq = self.next_timer_seq.get();
391        self.next_timer_seq.set(seq + 1);
392        self.timers
393            .borrow_mut()
394            .push(Reverse(Timer { at, seq, waker }));
395    }
396
397    /// When the soonest timer is due.
398    pub(crate) fn next_timer(&self) -> Option<Instant> {
399        self.timers.borrow().peek().map(|Reverse(t)| t.at)
400    }
401
402    /// Wakes the timers due at `now`.
403    pub(crate) fn fire_timers(&self, now: Instant) {
404        let mut due = Vec::new();
405        {
406            let mut timers = self.timers.borrow_mut();
407            while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
408                if let Some(Reverse(timer)) = timers.pop() {
409                    due.push(timer.waker);
410                }
411            }
412        }
413        for waker in due {
414            waker.wake();
415        }
416    }
417
418    /// A new id for a native animation node or animation.
419    pub(crate) fn next_animation_id(&self) -> u32 {
420        let n = self.animation_ids.get();
421        self.animation_ids.set(n + 1);
422        2 * n + 1
423    }
424
425    pub(crate) fn set_runtime(&self, runtime: Handle) {
426        *self.runtime.borrow_mut() = Some(runtime);
427    }
428
429    pub(crate) fn set_notify(&self, notify: Notify) {
430        *self.ready.notify.lock().expect("notify lock") = Some(notify);
431    }
432
433    fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
434        let id = {
435            let mut inner = self.inner.borrow_mut();
436            inner.next_task += 1;
437            let id = inner.next_task;
438            inner.tasks.insert(
439                id,
440                Entry {
441                    host,
442                    future: Some(future),
443                },
444            );
445            id
446        };
447        // Polled at the next run, not inside the code that spawned it.
448        self.ready.ids.lock().expect("ready lock").push(id);
449        let notify = self.ready.notify.lock().expect("notify lock").clone();
450        if let Some(notify) = notify {
451            notify();
452        }
453        id
454    }
455
456    fn cancel(&self, id: u64) {
457        let removed = self.inner.borrow_mut().tasks.remove(&id);
458        // Dropped outside the borrow: the future may own other tasks.
459        drop(removed);
460    }
461
462    /// Polls the woken tasks; returns whether there were any.
463    pub(crate) fn poll_ready(&self) -> bool {
464        let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
465        if ids.is_empty() {
466            return false;
467        }
468        ids.sort_unstable();
469        ids.dedup();
470        // tokio's timers, IO and `spawn` find their runtime here.
471        let runtime = self.runtime.borrow().clone();
472        let _context = runtime.as_ref().map(Handle::enter);
473        for id in ids {
474            let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
475                Some(entry) => entry.future.take(),
476                None => None,
477            };
478            let Some(mut future) = future else { continue };
479            let waker = Waker::from(Arc::new(TaskWaker {
480                id,
481                ready: self.ready.clone(),
482            }));
483            let done = match super::component::caught(|| {
484                future
485                    .as_mut()
486                    .poll(&mut TaskContext::from_waker(&waker))
487                    .is_ready()
488            }) {
489                Ok(done) => done,
490                // A task that panicked ends; its component failed.
491                Err(message) => {
492                    let mut inner = self.inner.borrow_mut();
493                    if let Some(entry) = inner.tasks.get(&id) {
494                        let host = entry.host;
495                        inner.failures.push((host, message));
496                    }
497                    true
498                }
499            };
500            if done {
501                self.inner.borrow_mut().tasks.remove(&id);
502                drop(future);
503            } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
504                entry.future = Some(future);
505            }
506        }
507        true
508    }
509
510    #[cfg(test)]
511    pub(crate) fn task_count(&self) -> usize {
512        self.inner.borrow().tasks.len()
513    }
514
515    /// The tasks that panicked since, by component.
516    pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
517        std::mem::take(&mut self.inner.borrow_mut().failures)
518    }
519
520    /// What tasks asked of the platform.
521    pub(crate) fn take_actions(&self) -> VecDeque<Action> {
522        std::mem::take(&mut self.inner.borrow_mut().actions)
523    }
524
525    pub(crate) fn act(&self, action: Action) {
526        self.inner.borrow_mut().actions.push_back(action);
527        let notify = self.ready.notify.lock().expect("notify lock").clone();
528        if let Some(notify) = notify {
529            notify();
530        }
531    }
532
533    /// Keeps `answer` until the events emitted so far have been handed to
534    /// JS and handled ([`super::after_answer`]).
535    pub(crate) fn after_answer(&self, answer: AfterAnswer) {
536        self.answers.borrow_mut().waiting.push(answer);
537    }
538
539    /// The events emitted so far go to JS: what waited for them is due.
540    pub(crate) fn hand_answers(&self) {
541        let mut answers = self.answers.borrow_mut();
542        let Answers { waiting, due } = &mut *answers;
543        if !waiting.is_empty() {
544            due.append(waiting);
545        }
546    }
547
548    /// Whether closures wait for the next commit to run.
549    pub(crate) fn has_due_answers(&self) -> bool {
550        !self.answers.borrow().due.is_empty()
551    }
552
553    /// Whether the queues ever held a closure (they allocate on the first).
554    #[cfg(test)]
555    pub(crate) fn answers_allocated(&self) -> bool {
556        let answers = self.answers.borrow();
557        answers.waiting.capacity() > 0 || answers.due.capacity() > 0
558    }
559
560    /// The closures whose events JS has handled, in order.
561    pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
562        std::mem::take(&mut self.answers.borrow_mut().due)
563    }
564}
565
566/// A running task of the core. Dropping it cancels the
567/// task (TS's `clearTimeout`, for timers); [`Task::detach`] lets it run
568/// on its own. Awaited in another task, it gives the task's output.
569#[must_use = "a dropped task is cancelled: keep it, or detach it"]
570pub struct Task<T> {
571    executor: Weak<Executor>,
572    id: u64,
573    output: Rc<RefCell<Output<T>>>,
574    detached: bool,
575}
576
577/// A value a future waits for, and the waker to call when it comes.
578pub(crate) struct Output<T> {
579    pub(crate) value: Option<T>,
580    pub(crate) waker: Option<Waker>,
581}
582
583/// Where an [`Answer`] comes from.
584pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
585
586impl<T> Default for Output<T> {
587    fn default() -> Self {
588        Self {
589            value: None,
590            waker: None,
591        }
592    }
593}
594
595impl<T> Output<T> {
596    /// Delivers `value`, waking the future waiting for it.
597    pub(crate) fn deliver(&mut self, value: T) {
598        self.value = Some(value);
599        if let Some(waker) = self.waker.take() {
600            waker.wake();
601        }
602    }
603}
604
605/// The answer the platform gives to a request (a dialog, an image's size),
606/// awaited in a task.
607#[must_use = "an answer does nothing unless awaited"]
608pub struct Answer<T> {
609    slot: Rc<RefCell<Output<T>>>,
610}
611
612/// The answer to a dialog (`nsh_base::alert_dialog`): the index of the
613/// button pressed, -1 when it was dismissed.
614pub type DialogAnswer = Answer<i32>;
615
616impl<T> Answer<T> {
617    pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
618        let slot = Rc::new(RefCell::new(Output::default()));
619        (Self { slot: slot.clone() }, slot)
620    }
621}
622
623impl<T> std::fmt::Debug for Answer<T> {
624    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
625        f.debug_struct("Answer").finish_non_exhaustive()
626    }
627}
628
629impl<T> Future for Answer<T> {
630    type Output = T;
631
632    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
633        let mut slot = self.slot.borrow_mut();
634        match slot.value.take() {
635            Some(value) => Poll::Ready(value),
636            None => {
637                slot.waker = Some(cx.waker().clone());
638                Poll::Pending
639            }
640        }
641    }
642}
643
644impl<T> std::fmt::Debug for Task<T> {
645    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646        f.debug_struct("Task")
647            .field("id", &self.id)
648            .finish_non_exhaustive()
649    }
650}
651
652impl<T> Task<T> {
653    /// Lets the task run to its end without this handle (it still ends
654    /// with its component).
655    pub fn detach(mut self) {
656        self.detached = true;
657    }
658}
659
660impl<T> Drop for Task<T> {
661    fn drop(&mut self) {
662        if !self.detached
663            && let Some(executor) = self.executor.upgrade()
664        {
665            executor.cancel(self.id);
666        }
667    }
668}
669
670impl<T> Future for Task<T> {
671    type Output = T;
672
673    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
674        let mut output = self.output.borrow_mut();
675        match output.value.take() {
676            Some(value) => Poll::Ready(value),
677            None => {
678                output.waker = Some(cx.waker().clone());
679                Poll::Pending
680            }
681        }
682    }
683}
684
685/// Starts `future` as a task of `host`, to run to its end.
686pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
687    executor.spawn(host, future)
688}
689
690/// Applies `action` after `delay`, as a task of `host` (dropping the task
691/// cancels it).
692pub(crate) fn act_after(
693    executor: &Rc<Executor>,
694    host: NodeId,
695    delay: Duration,
696    action: Action,
697) -> Task<()> {
698    let weak = Rc::downgrade(executor);
699    let acting = weak.clone();
700    // From now, not from when the task is first polled.
701    let at = crate::time::now() + delay;
702    let id = executor.spawn(
703        host,
704        Box::pin(async move {
705            super::timer_until(at).await;
706            if let Some(executor) = acting.upgrade() {
707                executor.act(action);
708            }
709        }),
710    );
711    Task {
712        executor: weak,
713        id,
714        output: Rc::new(RefCell::new(Output::default())),
715        detached: false,
716    }
717}
718
719/// Starts `future` on the engine thread, with no component (a task of a
720/// component that runs once: its owner ends it, [`TaskHandle::cancel`]).
721/// The task is detached: dropping it does not cancel it.
722pub(crate) fn spawn_future<R: 'static>(
723    executor: &Rc<Executor>,
724    future: impl Future<Output = R> + 'static,
725) -> Task<R> {
726    let weak = Rc::downgrade(executor);
727    let output = Rc::new(RefCell::new(Output {
728        value: None,
729        waker: None,
730    }));
731    let done = output.clone();
732    let id = executor.spawn(
733        0,
734        Box::pin(async move {
735            let value = future.await;
736            let mut output = done.borrow_mut();
737            output.value = Some(value);
738            if let Some(waker) = output.waker.take() {
739                waker.wake();
740            }
741        }),
742    );
743    Task {
744        executor: weak,
745        id,
746        output,
747        detached: true,
748    }
749}
750
751/// What cancels a task, apart from its handle.
752pub(crate) struct TaskHandle {
753    executor: Weak<Executor>,
754    id: u64,
755}
756
757impl TaskHandle {
758    /// Ends the task (nothing when it ended already).
759    pub(crate) fn cancel(&self) {
760        if let Some(executor) = self.executor.upgrade() {
761            executor.cancel(self.id);
762        }
763    }
764}
765
766impl<T> Task<T> {
767    /// What cancels it.
768    pub(crate) fn handle(&self) -> TaskHandle {
769        TaskHandle {
770            executor: self.executor.clone(),
771            id: self.id,
772        }
773    }
774}