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