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