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    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
34/// Called when a task is woken (from any thread): the engine wakes up.
35pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
36
37/// Tasks woken since the last run.
38#[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
63/// What a component or a task asks of the platform, applied by the core.
64pub(crate) enum Action {
65    Command(NodeId, Command),
66    /// A dialog; its answer resolves the slot.
67    Dialog(Dialog, Rc<RefCell<Output<i32>>>),
68    /// The result of a module function JS waits for.
69    Return(u32, super::JsResult),
70    /// The pixel size of the image at the URI (its bytes stay loaded); the
71    /// answer resolves the slot.
72    ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
73    /// An HTTP request for the engine's network stack; the response (or
74    /// its failure) resolves the slot.
75    Fetch(
76        Box<crate::platform::HttpRequest>,
77        AnswerSlot<Result<super::services::HttpResponse, super::services::FetchFailure>>,
78    ),
79    /// Reads the system clipboard; the answer resolves the slot.
80    ReadClipboard(ClipboardRead),
81    /// Runs a function on the platform's main thread, after the commit.
82    MainThread(crate::main_thread::MainThreadTask),
83    /// Registers a font (TrueType, OpenType, WOFF or WOFF2 data); its family
84    /// name, or why it is no font, resolves the slot.
85    RegisterFont(Vec<u8>, AnswerSlot<Result<String, String>>),
86    /// Shows the system's picker for images; the files picked (none when
87    /// cancelled) resolve the slot.
88    PickImages(
89        crate::picker::PickRequest,
90        AnswerSlot<Vec<crate::picker::PickedFile>>,
91    ),
92    /// Shows the system's picker for files of any type; the files picked
93    /// (none when cancelled) resolve the slot.
94    PickFiles(
95        crate::picker::FilePickRequest,
96        AnswerSlot<Vec<crate::picker::PickedFile>>,
97    ),
98    /// Calls function `name` of the embedding app (`nsh/host`); its
99    /// value, or why it failed, resolves the slot.
100    HostCall {
101        name: String,
102        args: crate::JsonValue,
103        answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
104    },
105    /// Hands data to function `name` of the embedding app, with no answer
106    /// (`nsh/host`'s `post`).
107    HostPost {
108        name: String,
109        args: crate::JsonValue,
110    },
111    /// Drops the slots of the host calls whose answers are gone (they
112    /// timed out).
113    ForgetHostCalls,
114    /// Opens a URL outside the app (checked by
115    /// [`crate::open_url::check_url`]); whether it opened resolves the
116    /// slot.
117    OpenUrl(String, AnswerSlot<bool>),
118    /// Lets the user pick a color on the screen; the color (none when
119    /// cancelled or not supported) resolves the slot.
120    PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
121    /// A speech recognition session's request ([`crate::speech`]).
122    Speech(SpeechAction),
123    /// A notification's request ([`crate::notifications`]).
124    Notification(NotificationAction),
125    /// The next link the system hands the app ([`crate::url_scheme`])
126    /// resolves the slot, those that came before first.
127    NextUrlSchemeOpen(AnswerSlot<String>),
128    /// The next files the system opens the app with
129    /// ([`crate::file_type`]) resolve the slot, all that came before at
130    /// once.
131    NextOpenFiles(AnswerSlot<Vec<std::path::PathBuf>>),
132    /// The next later launch of the app
133    /// ([`crate::single_instance::SecondInstance`]) resolves the slot, those
134    /// that came before first.
135    NextSecondInstance(AnswerSlot<crate::single_instance::SecondInstance>),
136    /// The next address move the app did not make
137    /// ([`crate::url_scheme::AppUrlChange`]) resolves the slot.
138    NextAppUrlChange(AnswerSlot<crate::url_scheme::AppUrlChange>),
139    /// The app's address resolves the slot ([`crate::url_scheme`]).
140    AppUrl(AnswerSlot<Option<String>>),
141    /// The app sets its address ([`crate::url_scheme`]), replacing the
142    /// history entry's or pushing one.
143    SetAppUrl(String, crate::url_scheme::HistoryBehavior),
144    /// A sound's or a player's request ([`crate::audio`]).
145    Audio(AudioAction),
146    /// Whether a web view's ref gives its page trusted input here
147    /// (`sendInput`): the platform delivers it and the app holds
148    /// `webview.input`; the answer resolves the slot.
149    WebInputAvailable(AnswerSlot<bool>),
150    /// Whether a web view's ref evaluates scripts here.
151    WebEvaluateAvailable(AnswerSlot<bool>),
152    /// Whether a web view shows a page here: the platform shows web views
153    /// and the app holds `webview`; the answer resolves the slot.
154    WebViewAvailable(AnswerSlot<bool>),
155    /// A request on local paths for the platform
156    /// ([`crate::file_dialog`]); its answer resolves the slot.
157    FileRequest(crate::file_dialog::FileRequest, FileAnswer),
158    /// An operation on the native animation graph.
159    Animation(crate::animation::AnimationOp),
160    /// Starts an animation; its end resolves the slot.
161    Animate {
162        op: crate::animation::AnimationOp,
163        animation: crate::animation::AnimationId,
164        end: AnswerSlot<bool>,
165    },
166    /// Reads a node's value where it moves; the value resolves the slot.
167    ReadValue {
168        node: crate::animation::NodeId,
169        value: AnswerSlot<f32>,
170    },
171    /// A component's own list reports the rows viewable now (they stayed
172    /// so for its minimum view time).
173    ReportViewable(NodeId),
174    /// A hint overlay's delay is over with the pointer on its anchor: it
175    /// shows.
176    Hint(NodeId),
177    /// The start of the next display frame resolves the slot.
178    Frame(AnswerSlot<Instant>),
179    /// Sets the app's appearance.
180    Appearance(crate::platform::Appearance),
181    /// Sets the app's design tokens.
182    Tokens(super::Tokens),
183    /// Sets the app's translations ([`crate::i18n`]).
184    Translations(crate::i18n::Translations),
185    /// Shows the app in a language whatever the user's (`None`: the
186    /// user's again).
187    Locale(Option<crate::platform::Locale>),
188    /// Draws the scroll views' bars with the built-in bar the source makes
189    /// of the theme, or (no theme) with the platform's indicator.
190    BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
191    /// Measures the node with the layout of the commit the action goes out
192    /// with; the measurement resolves the slot.
193    Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
194    /// Measures where the list's viewport starts among its rows with the
195    /// layout of the commit the action goes out with; the position
196    /// resolves the slot.
197    MeasureScrollPosition(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>),
198    /// Evaluates a web view's script within a timeout, with its answer
199    /// kept by the core.
200    Evaluate(
201        NodeId,
202        String,
203        std::time::Duration,
204        crate::platform::web_evaluation::Slot,
205    ),
206    /// Rejects a request that exceeded its deadline.
207    WebEvaluationTimeout(u32),
208    /// How long the node's transitions run with the styles of the commit
209    /// the action goes out with; the time resolves the slot.
210    TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
211    /// Presses what a pointer at the press's page position would inside
212    /// the node, with the layout of the commit the action goes out with;
213    /// whether a view took it resolves the slot.
214    PressAt(NodeId, crate::PressEvent, AnswerSlot<bool>),
215}
216
217/// What a speech recognition session asks of the core
218/// ([`Action::Speech`]).
219pub(crate) enum SpeechAction {
220    /// Starts session `id`, reporting to `sink`; the session running is
221    /// aborted first.
222    Start {
223        id: u32,
224        request: crate::speech::SpeechRequest,
225        sink: crate::speech::SpeechSink,
226    },
227    /// Stops session `id`: it finishes what it heard, then ends.
228    Stop(u32),
229    /// Ends session `id` at once, without an error.
230    Abort(u32),
231    /// Whether speech can be recognized; the answer resolves the slot.
232    Available(AnswerSlot<bool>),
233}
234
235/// What a sound or a player asks of the core ([`Action::Audio`]).
236pub(crate) enum AudioAction {
237    /// Opens sound or player `id` (its first command, a
238    /// [`crate::audio::AudioCommand::Load`] or
239    /// [`crate::audio::AudioCommand::Open`]), reporting to `sink`.
240    Open {
241        command: crate::audio::AudioCommand,
242        sink: crate::audio::AudioSink,
243    },
244    /// A command of an open sound or player; an unload or close ends it.
245    Command(crate::audio::AudioCommand),
246    /// Whether sound plays here; the answer resolves the slot.
247    Available(AnswerSlot<bool>),
248}
249
250/// What the app asks about notifications ([`Action::Notification`]).
251pub(crate) enum NotificationAction {
252    /// The permission; with `ask`, the user is asked first when they were
253    /// not yet. The answer resolves the slot.
254    Permission {
255        ask: bool,
256        answer: AnswerSlot<crate::notifications::NotificationPermission>,
257    },
258    /// Shows a notification; whether the system took it resolves the slot.
259    Show {
260        notification: crate::notifications::Notification,
261        answer: AnswerSlot<bool>,
262    },
263    /// Removes the notification called this.
264    Close(String),
265    /// Sets the app's badge.
266    SetBadge(u32),
267    /// The id of the next notification pressed resolves the slot.
268    NextPress(AnswerSlot<String>),
269}
270
271/// A request on local paths waiting for the platform's answer
272/// ([`Action::FileRequest`]).
273pub(crate) enum FileAnswer {
274    /// The paths picked in the open dialog, none when cancelled.
275    OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
276    /// The path chosen in the save dialog, none when cancelled.
277    SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
278    /// The path opened or showed in the file manager, or why not.
279    Done(AnswerSlot<Result<(), String>>),
280    /// Where the trashed item went, or why it was not.
281    Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
282}
283
284impl FileAnswer {
285    /// Answers with the platform's `paths` (none: cancelled), or its
286    /// `error`.
287    pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
288        match self {
289            FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
290                Some(error) => Err(error),
291                None => Ok((!paths.is_empty()).then_some(paths)),
292            }),
293            FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
294                Some(error) => Err(error),
295                None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
296            }),
297            FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
298                Some(error) => Err(error),
299                None => Ok(()),
300            }),
301            FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
302                Some(error) => Err(error),
303                None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
304            }),
305        }
306    }
307}
308
309/// A clipboard read waiting for the platform's answer.
310pub(crate) enum ClipboardRead {
311    /// The text (`""` when it holds none).
312    Text(AnswerSlot<String>),
313    /// Whether it holds text.
314    Has(AnswerSlot<bool>),
315    /// The image (`None` when it holds none, or one over
316    /// [`crate::platform::clipboard::MAX_IMAGE_BYTES`]).
317    Image(AnswerSlot<Option<ClipboardImage>>),
318    /// The image for `Clipboard.readImage`: `Err` with the size in encoded
319    /// bytes of one over [`crate::platform::clipboard::MAX_IMAGE_BYTES`].
320    CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
321    /// Whether it holds an image.
322    HasImage(AnswerSlot<bool>),
323    /// The `file:` URLs of the local files on it.
324    Files(AnswerSlot<Vec<String>>),
325}
326
327/// An image read from the system clipboard (`Clipboard.readImage`).
328#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
329pub struct ClipboardImage {
330    /// A URL of the image that an `Image` shows (its `src`) and `fetch`
331    /// reads the bytes of; `Clipboard.writeImage` takes it back.
332    pub url: String,
333    /// Its size in pixels, as decoded.
334    pub size: Size<DevicePixels>,
335}
336
337/// An image's size in pixels (`Image.getSize`); TS: `PixelSize`.
338#[derive(Debug, Clone, Copy, Default, PartialEq)]
339pub struct ImageSize {
340    /// Width.
341    pub width: DevicePixels,
342    /// Height.
343    pub height: DevicePixels,
344}
345
346impl ImageSize {
347    /// As a [`Size`].
348    pub fn size(&self) -> Size<DevicePixels> {
349        Size::new(self.width, self.height)
350    }
351}
352
353impl From<ImageSize> for Size<DevicePixels> {
354    fn from(s: ImageSize) -> Self {
355        s.size()
356    }
357}
358
359/// TS: `PixelSize` (`{ width, height }`).
360impl super::JsValue for ImageSize {
361    fn ts_type(types: &mut super::TsTypes) -> String {
362        <Size<DevicePixels> as super::JsValue>::ts_type(types)
363    }
364
365    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
366        if value.kind() != super::JsKind::Object {
367            return Err(value.expected("an object"));
368        }
369        let side = |key: &str| -> Result<DevicePixels, super::PropError> {
370            let v = value.field(key)?;
371            DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
372        };
373        Ok(ImageSize {
374            width: side("width")?,
375            height: side("height")?,
376        })
377    }
378
379    fn to_js<'a>(
380        &self,
381        host: &'a dyn super::JsHost,
382    ) -> Result<super::JsOwned<'a>, super::PropError> {
383        let owned = super::JsOwned::new(host, host.new_object()?);
384        let object = owned.get().raw();
385        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
386        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
387        Ok(owned)
388    }
389}
390
391/// The status bar's base setting, as a command for the surface's root.
392pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
393    Action::Command(ROOT_ID, Command::SetStatusBar(patch))
394}
395
396struct Entry {
397    host: NodeId,
398    /// Out while it is polled.
399    future: Option<LocalFuture>,
400}
401
402#[derive(Default)]
403struct Inner {
404    tasks: FxHashMap<u64, Entry>,
405    next_task: u64,
406    actions: VecDeque<Action>,
407    failures: Vec<(NodeId, String)>,
408}
409
410/// The executor of one core's component tasks.
411#[derive(Default)]
412pub(crate) struct Executor {
413    inner: RefCell<Inner>,
414    ready: Arc<Ready>,
415    /// The runtime tasks are polled in the context of.
416    runtime: RefCell<Option<Handle>>,
417    /// Native animation nodes and animations made so far (their ids are
418    /// odd: JS's are even).
419    animation_ids: std::cell::Cell<u32>,
420    /// Live derived nodes, for what derives them again (a region or a row
421    /// made again).
422    derived: RefCell<super::animated::Derived>,
423    /// The components' listeners of the back button.
424    pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
425    /// What runs as the app quits ([`super::desktop::on_app_quit`]).
426    pub(crate) quit: Rc<RefCell<super::quit::QuitListeners>>,
427    /// The quit listeners' work still running ([`crate::Core::start_quit`]).
428    pub(crate) quitting: Rc<std::cell::Cell<usize>>,
429    /// The views' keyboard shortcuts.
430    pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
431    /// The views' menus' handlers.
432    pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
433    /// The views' watches of nodes they did not make.
434    pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
435    /// The timers tasks wait for ([`super::timer`]): the core fires them as
436    /// they come due, and the engine's loop wakes for the soonest, as it does
437    /// for JS's timers.
438    timers: Arc<Timers>,
439    /// What waits for the app to answer the events emitted before it
440    /// ([`super::after_answer`]).
441    answers: RefCell<Answers>,
442    /// The engine's sounds ([`super::audio`]).
443    pub(crate) sounds: RefCell<super::audio::Sounds>,
444}
445
446/// The closures of [`super::after_answer`], by how far their events went.
447#[derive(Default)]
448struct Answers {
449    /// Their events have not been handed to JS yet.
450    waiting: Vec<AfterAnswer>,
451    /// Their events went to JS: they run in the next commit, by when JS has
452    /// handled them and its ops are applied.
453    due: Vec<AfterAnswer>,
454}
455
456/// A closure of [`super::after_answer`] and the owner it runs under.
457pub(crate) struct AfterAnswer {
458    pub(crate) owner: super::Owner,
459    pub(crate) f: Box<dyn FnOnce()>,
460}
461
462/// The timers tasks wait for, soonest first (in the order they were made
463/// among timers due at once). Shared with the [`TimerKey`]s of the delays
464/// waiting (which are `Send`, as delays are), so a delay dropped before its
465/// time takes its timer and waker back at once, wherever it is dropped.
466#[derive(Default)]
467struct Timers(Mutex<TimerQueue>);
468
469#[derive(Default)]
470struct TimerQueue {
471    next_seq: u64,
472    wakers: BTreeMap<(Instant, u64), Waker>,
473}
474
475impl Timers {
476    fn queue(&self) -> std::sync::MutexGuard<'_, TimerQueue> {
477        self.0
478            .lock()
479            .unwrap_or_else(std::sync::PoisonError::into_inner)
480    }
481}
482
483/// A timer waiting in the executor ([`Executor::add_timer`]); dropping it
484/// takes the timer back.
485#[derive(Debug)]
486pub(crate) struct TimerKey {
487    timers: std::sync::Weak<Timers>,
488    key: (Instant, u64),
489}
490
491impl TimerKey {
492    /// Wakes `waker` instead when the timer fires (the delay was polled
493    /// again by another task's waker).
494    pub(crate) fn set_waker(&self, waker: &Waker) {
495        let Some(timers) = self.timers.upgrade() else {
496            return;
497        };
498        let old = {
499            let mut queue = timers.queue();
500            match queue.wakers.get_mut(&self.key) {
501                Some(kept) if !kept.will_wake(waker) => {
502                    Some(std::mem::replace(kept, waker.clone()))
503                }
504                _ => None,
505            }
506        };
507        // Dropped outside the lock.
508        drop(old);
509    }
510}
511
512impl Drop for TimerKey {
513    fn drop(&mut self) {
514        let Some(timers) = self.timers.upgrade() else {
515            return;
516        };
517        let waker = timers.queue().wakers.remove(&self.key);
518        drop(waker);
519    }
520}
521
522impl Executor {
523    /// The derived nodes and their handles.
524    pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
525        self.derived.borrow_mut()
526    }
527
528    /// Wakes `waker` at `at`, unless the key is dropped first.
529    pub(crate) fn add_timer(&self, at: Instant, waker: Waker) -> TimerKey {
530        let mut queue = self.timers.queue();
531        let key = (at, queue.next_seq);
532        queue.next_seq += 1;
533        queue.wakers.insert(key, waker);
534        TimerKey {
535            timers: Arc::downgrade(&self.timers),
536            key,
537        }
538    }
539
540    /// When the soonest timer is due.
541    pub(crate) fn next_timer(&self) -> Option<Instant> {
542        self.timers
543            .queue()
544            .wakers
545            .first_key_value()
546            .map(|(&(at, _), _)| at)
547    }
548
549    /// Wakes the timers due at `now`.
550    pub(crate) fn fire_timers(&self, now: Instant) {
551        let mut due = Vec::new();
552        {
553            let mut queue = self.timers.queue();
554            while let Some(timer) = queue.wakers.first_entry()
555                && timer.key().0 <= now
556            {
557                due.push(timer.remove());
558            }
559        }
560        // Woken outside the lock: a waker may drop delays.
561        for waker in due {
562            waker.wake();
563        }
564    }
565
566    /// A new id for a native animation node or animation.
567    pub(crate) fn next_animation_id(&self) -> u32 {
568        let n = self.animation_ids.get();
569        self.animation_ids.set(n + 1);
570        2 * n + 1
571    }
572
573    pub(crate) fn set_runtime(&self, runtime: Handle) {
574        *self.runtime.borrow_mut() = Some(runtime);
575    }
576
577    /// The runtime tasks are polled in the context of, if one is set.
578    #[cfg(not(target_arch = "wasm32"))]
579    pub(crate) fn runtime(&self) -> Option<Handle> {
580        self.runtime.borrow().clone()
581    }
582
583    pub(crate) fn set_notify(&self, notify: Notify) {
584        *self.ready.notify.lock().expect("notify lock") = Some(notify);
585    }
586
587    fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
588        let id = {
589            let mut inner = self.inner.borrow_mut();
590            inner.next_task += 1;
591            let id = inner.next_task;
592            inner.tasks.insert(
593                id,
594                Entry {
595                    host,
596                    future: Some(future),
597                },
598            );
599            id
600        };
601        // Polled at the next run, not inside the code that spawned it.
602        self.ready.ids.lock().expect("ready lock").push(id);
603        let notify = self.ready.notify.lock().expect("notify lock").clone();
604        if let Some(notify) = notify {
605            notify();
606        }
607        id
608    }
609
610    fn cancel(&self, id: u64) {
611        let removed = self.inner.borrow_mut().tasks.remove(&id);
612        // Dropped outside the borrow: the future may own other tasks.
613        drop(removed);
614    }
615
616    /// Polls the woken tasks; returns whether there were any.
617    pub(crate) fn poll_ready(&self) -> bool {
618        let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
619        if ids.is_empty() {
620            return false;
621        }
622        ids.sort_unstable();
623        ids.dedup();
624        // tokio's timers, IO and `spawn` find their runtime here.
625        let runtime = self.runtime.borrow().clone();
626        let _context = runtime.as_ref().map(Handle::enter);
627        for id in ids {
628            let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
629                Some(entry) => entry.future.take(),
630                None => None,
631            };
632            let Some(mut future) = future else { continue };
633            let waker = Waker::from(Arc::new(TaskWaker {
634                id,
635                ready: self.ready.clone(),
636            }));
637            let done = match super::component::caught(|| {
638                future
639                    .as_mut()
640                    .poll(&mut TaskContext::from_waker(&waker))
641                    .is_ready()
642            }) {
643                Ok(done) => done,
644                // A task that panicked ends; its component failed.
645                Err(message) => {
646                    let mut inner = self.inner.borrow_mut();
647                    if let Some(entry) = inner.tasks.get(&id) {
648                        let host = entry.host;
649                        inner.failures.push((host, message));
650                    }
651                    true
652                }
653            };
654            if done {
655                self.inner.borrow_mut().tasks.remove(&id);
656                drop(future);
657            } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
658                entry.future = Some(future);
659            }
660        }
661        true
662    }
663
664    #[cfg(test)]
665    pub(crate) fn task_count(&self) -> usize {
666        self.inner.borrow().tasks.len()
667    }
668
669    /// The tasks that panicked since, by component.
670    pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
671        std::mem::take(&mut self.inner.borrow_mut().failures)
672    }
673
674    /// What tasks asked of the platform.
675    pub(crate) fn take_actions(&self) -> VecDeque<Action> {
676        std::mem::take(&mut self.inner.borrow_mut().actions)
677    }
678
679    pub(crate) fn act(&self, action: Action) {
680        self.inner.borrow_mut().actions.push_back(action);
681        let notify = self.ready.notify.lock().expect("notify lock").clone();
682        if let Some(notify) = notify {
683            notify();
684        }
685    }
686
687    /// Keeps `answer` until the events emitted so far have been handed to
688    /// JS and handled ([`super::after_answer`]).
689    pub(crate) fn after_answer(&self, answer: AfterAnswer) {
690        self.answers.borrow_mut().waiting.push(answer);
691    }
692
693    /// The events emitted so far go to JS: what waited for them is due.
694    pub(crate) fn hand_answers(&self) {
695        let mut answers = self.answers.borrow_mut();
696        let Answers { waiting, due } = &mut *answers;
697        if !waiting.is_empty() {
698            due.append(waiting);
699        }
700    }
701
702    /// Whether closures wait for the next commit to run.
703    pub(crate) fn has_due_answers(&self) -> bool {
704        !self.answers.borrow().due.is_empty()
705    }
706
707    /// Whether the queues ever held a closure (they allocate on the first).
708    #[cfg(test)]
709    pub(crate) fn answers_allocated(&self) -> bool {
710        let answers = self.answers.borrow();
711        answers.waiting.capacity() > 0 || answers.due.capacity() > 0
712    }
713
714    /// The closures whose events JS has handled, in order.
715    pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
716        std::mem::take(&mut self.answers.borrow_mut().due)
717    }
718}
719
720/// A running task of the core. Dropping it cancels the
721/// task (TS's `clearTimeout`, for timers); [`Task::detach`] lets it run
722/// on its own. Awaited in another task, it gives the task's output.
723#[must_use = "a dropped task is cancelled: keep it, or detach it"]
724pub struct Task<T> {
725    executor: Weak<Executor>,
726    id: u64,
727    output: Rc<RefCell<Output<T>>>,
728    detached: bool,
729}
730
731/// A value a future waits for, and the waker to call when it comes.
732pub(crate) struct Output<T> {
733    pub(crate) value: Option<T>,
734    pub(crate) waker: Option<Waker>,
735}
736
737/// Where an [`Answer`] comes from.
738pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
739
740impl<T> Default for Output<T> {
741    fn default() -> Self {
742        Self {
743            value: None,
744            waker: None,
745        }
746    }
747}
748
749impl<T> Output<T> {
750    /// Delivers `value`, waking the future waiting for it.
751    pub(crate) fn deliver(&mut self, value: T) {
752        self.value = Some(value);
753        if let Some(waker) = self.waker.take() {
754            waker.wake();
755        }
756    }
757}
758
759/// The answer the platform gives to a request (a dialog, an image's size),
760/// awaited in a task.
761#[must_use = "an answer does nothing unless awaited"]
762pub struct Answer<T> {
763    slot: Rc<RefCell<Output<T>>>,
764}
765
766/// The answer to a dialog (`nsh_base::alert_dialog`): the index of the
767/// button pressed, -1 when it was dismissed.
768pub type DialogAnswer = Answer<i32>;
769
770impl<T> Answer<T> {
771    pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
772        let slot = Rc::new(RefCell::new(Output::default()));
773        (Self { slot: slot.clone() }, slot)
774    }
775}
776
777impl<T> std::fmt::Debug for Answer<T> {
778    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779        f.debug_struct("Answer").finish_non_exhaustive()
780    }
781}
782
783impl<T> Future for Answer<T> {
784    type Output = T;
785
786    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
787        let mut slot = self.slot.borrow_mut();
788        match slot.value.take() {
789            Some(value) => Poll::Ready(value),
790            None => {
791                slot.waker = Some(cx.waker().clone());
792                Poll::Pending
793            }
794        }
795    }
796}
797
798impl<T> std::fmt::Debug for Task<T> {
799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800        f.debug_struct("Task")
801            .field("id", &self.id)
802            .finish_non_exhaustive()
803    }
804}
805
806impl<T> Task<T> {
807    /// Lets the task run to its end without this handle (it still ends
808    /// with its component).
809    pub fn detach(mut self) {
810        self.detached = true;
811    }
812}
813
814impl<T> Drop for Task<T> {
815    fn drop(&mut self) {
816        if !self.detached
817            && let Some(executor) = self.executor.upgrade()
818        {
819            executor.cancel(self.id);
820        }
821    }
822}
823
824impl<T> Future for Task<T> {
825    type Output = T;
826
827    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
828        let mut output = self.output.borrow_mut();
829        match output.value.take() {
830            Some(value) => Poll::Ready(value),
831            None => {
832                output.waker = Some(cx.waker().clone());
833                Poll::Pending
834            }
835        }
836    }
837}
838
839/// Starts `future` as a task of `host`, to run to its end.
840pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
841    executor.spawn(host, future)
842}
843
844/// Applies `action` after `delay`, as a task of `host` (dropping the task
845/// cancels it).
846pub(crate) fn act_after(
847    executor: &Rc<Executor>,
848    host: NodeId,
849    delay: Duration,
850    action: Action,
851) -> Task<()> {
852    let weak = Rc::downgrade(executor);
853    let acting = weak.clone();
854    // From now, not from when the task is first polled.
855    let at = crate::time::now() + delay;
856    let id = executor.spawn(
857        host,
858        Box::pin(async move {
859            super::timer_until(at).await;
860            if let Some(executor) = acting.upgrade() {
861                executor.act(action);
862            }
863        }),
864    );
865    Task {
866        executor: weak,
867        id,
868        output: Rc::new(RefCell::new(Output::default())),
869        detached: false,
870    }
871}
872
873/// Starts `future` on the engine thread, with no component (a task of a
874/// component that runs once: its owner ends it, [`TaskHandle::cancel`]).
875/// The task is detached: dropping it does not cancel it.
876pub(crate) fn spawn_future<R: 'static>(
877    executor: &Rc<Executor>,
878    future: impl Future<Output = R> + 'static,
879) -> Task<R> {
880    let weak = Rc::downgrade(executor);
881    let output = Rc::new(RefCell::new(Output {
882        value: None,
883        waker: None,
884    }));
885    let done = output.clone();
886    let id = executor.spawn(
887        0,
888        Box::pin(async move {
889            let value = future.await;
890            let mut output = done.borrow_mut();
891            output.value = Some(value);
892            if let Some(waker) = output.waker.take() {
893                waker.wake();
894            }
895        }),
896    );
897    Task {
898        executor: weak,
899        id,
900        output,
901        detached: true,
902    }
903}
904
905/// What cancels a task, apart from its handle.
906pub(crate) struct TaskHandle {
907    executor: Weak<Executor>,
908    id: u64,
909}
910
911impl TaskHandle {
912    /// Ends the task (nothing when it ended already).
913    pub(crate) fn cancel(&self) {
914        if let Some(executor) = self.executor.upgrade() {
915            executor.cancel(self.id);
916        }
917    }
918}
919
920impl<T> Task<T> {
921    /// What cancels it.
922    pub(crate) fn handle(&self) -> TaskHandle {
923        TaskHandle {
924            executor: self.executor.clone(),
925            id: self.id,
926        }
927    }
928}