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