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