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