Skip to main content

nsh_core/element/
task.rs

1//! Async tasks ([`super::spawn`]): futures run on the engine thread (they
2//! may hold signals and other `!Send` handles) by a small executor of the
3//! core, polled inside a tokio runtime's context, so the tokio ecosystem
4//! works in them: network and file IO, channels; `Send` work goes to the
5//! runtime's threads ([`super::background`]). Their timers
6//! ([`super::timer`]) are the executor's own: the core fires them as they
7//! come due and the engine's loop wakes for the soonest, as for JS's.
8//! Wakers may fire on any thread: they wake the engine. A task changes
9//! what it wants by writing signals; it ends with the owner it was made
10//! under.
11
12use std::{
13    cell::RefCell,
14    cmp::Reverse,
15    collections::{BinaryHeap, VecDeque},
16    future::Future,
17    pin::Pin,
18    rc::{Rc, Weak},
19    sync::{Arc, Mutex},
20    task::{Context as TaskContext, Poll, Wake, Waker},
21    time::Duration,
22};
23
24use rustc_hash::FxHashMap;
25use tokio::runtime::Handle;
26
27use crate::{
28    Command, Dialog, NodeId, ROOT_ID, StatusBarSetting,
29    geometry::{DevicePixels, Size},
30    time::Instant,
31};
32
33type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
34
35/// Called when a task is woken (from any thread): the engine wakes up.
36pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
37
38/// Tasks woken since the last run.
39#[derive(Default)]
40struct Ready {
41    ids: Mutex<Vec<u64>>,
42    notify: Mutex<Option<Notify>>,
43}
44
45struct TaskWaker {
46    id: u64,
47    ready: Arc<Ready>,
48}
49
50impl Wake for TaskWaker {
51    fn wake(self: Arc<Self>) {
52        self.wake_by_ref();
53    }
54
55    fn wake_by_ref(self: &Arc<Self>) {
56        self.ready.ids.lock().expect("ready lock").push(self.id);
57        let notify = self.ready.notify.lock().expect("notify lock").clone();
58        if let Some(notify) = notify {
59            notify();
60        }
61    }
62}
63
64/// What a component or a task asks of the platform, applied by the core.
65pub(crate) enum Action {
66    Command(NodeId, Command),
67    /// A dialog; its answer resolves the slot.
68    Dialog(Dialog, Rc<RefCell<Output<i32>>>),
69    /// The result of a module function JS waits for.
70    Return(u32, super::JsResult),
71    /// The pixel size of the image at the URI (its bytes stay loaded); the
72    /// answer resolves the slot.
73    ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
74    /// An HTTP request for the engine's network stack; the response (or
75    /// its failure) resolves the slot.
76    Fetch(
77        Box<crate::platform::HttpRequest>,
78        AnswerSlot<Result<super::services::HttpResponse, String>>,
79    ),
80    /// Reads the system clipboard; the answer resolves the slot.
81    ReadClipboard(ClipboardRead),
82    /// Shows the system's picker for images; the files picked (none when
83    /// cancelled) resolve the slot.
84    PickImages(
85        crate::picker::PickRequest,
86        AnswerSlot<Vec<crate::picker::PickedFile>>,
87    ),
88    /// Calls function `name` of the embedding app (`nsh/host`); its
89    /// value, or why it failed, resolves the slot.
90    HostCall {
91        name: String,
92        args: crate::JsonValue,
93        answer: AnswerSlot<Result<crate::JsonValue, String>>,
94    },
95    /// Drops the slots of the host calls whose answers are gone (they
96    /// timed out).
97    ForgetHostCalls,
98    /// Opens a URL outside the app (checked by
99    /// [`crate::open_url::check_url`]); whether it opened resolves the
100    /// slot.
101    OpenUrl(String, AnswerSlot<bool>),
102    /// An operation on the native animation graph.
103    Animation(crate::animation::AnimationOp),
104    /// Starts an animation; its end resolves the slot.
105    Animate {
106        op: crate::animation::AnimationOp,
107        animation: crate::animation::AnimationId,
108        end: AnswerSlot<bool>,
109    },
110    /// Reads a node's value where it moves; the value resolves the slot.
111    ReadValue {
112        node: crate::animation::NodeId,
113        value: AnswerSlot<f32>,
114    },
115    /// A component's own list reports the rows viewable now (they stayed
116    /// so for its minimum view time).
117    ReportViewable(NodeId),
118    /// A hint overlay's delay is over with the pointer on its anchor: it
119    /// shows.
120    Hint(NodeId),
121    /// The start of the next display frame resolves the slot.
122    Frame(AnswerSlot<Instant>),
123    /// Sets the app's appearance.
124    Appearance(crate::platform::Appearance),
125    /// Measures the node with the layout of the commit the action goes out
126    /// with; the measurement resolves the slot.
127    Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
128}
129
130/// A clipboard read waiting for the platform's answer.
131pub(crate) enum ClipboardRead {
132    /// The text (`""` when it holds none).
133    Text(AnswerSlot<String>),
134    /// Whether it holds text.
135    Has(AnswerSlot<bool>),
136    /// The image (`None` when it holds none).
137    Image(AnswerSlot<Option<ClipboardImage>>),
138    /// Whether it holds an image.
139    HasImage(AnswerSlot<bool>),
140    /// The `file:` URLs of the local files on it.
141    Files(AnswerSlot<Vec<String>>),
142}
143
144/// An image read from the system clipboard (`Clipboard.readImage`).
145#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
146pub struct ClipboardImage {
147    /// The image as a `data:` URL (`data:image/png;base64,…`): an image's
148    /// `src`, and `fetch(url)` gives its bytes.
149    pub url: String,
150    /// Its size in pixels.
151    pub size: Size<DevicePixels>,
152}
153
154/// An image's size in pixels (`Image.getSize`); TS: `ImageSize`, an alias of
155/// `Size`.
156#[derive(Debug, Clone, Copy, Default, PartialEq)]
157pub struct ImageSize {
158    /// Width.
159    pub width: DevicePixels,
160    /// Height.
161    pub height: DevicePixels,
162}
163
164impl ImageSize {
165    /// As a [`Size`].
166    pub fn size(&self) -> Size<DevicePixels> {
167        Size::new(self.width, self.height)
168    }
169}
170
171impl From<ImageSize> for Size<DevicePixels> {
172    fn from(s: ImageSize) -> Self {
173        s.size()
174    }
175}
176
177/// TS: `type ImageSize = Size` (`{ width, height }`, in pixels here).
178impl super::JsValue for ImageSize {
179    fn ts_type(types: &mut super::TsTypes) -> String {
180        types.declare("ImageSize", |_| {
181            "/** An image's size in pixels (`Image.getSize`). */\nexport type ImageSize = Size;"
182                .into()
183        })
184    }
185
186    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
187        if value.kind() != super::JsKind::Object {
188            return Err(value.expected("an object"));
189        }
190        let side = |key: &str| -> Result<DevicePixels, super::PropError> {
191            let v = value.field(key)?;
192            DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
193        };
194        Ok(ImageSize {
195            width: side("width")?,
196            height: side("height")?,
197        })
198    }
199
200    fn to_js<'a>(
201        &self,
202        host: &'a dyn super::JsHost,
203    ) -> Result<super::JsOwned<'a>, super::PropError> {
204        let owned = super::JsOwned::new(host, host.new_object()?);
205        let object = owned.get().raw();
206        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
207        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
208        Ok(owned)
209    }
210}
211
212/// The status bar's base setting, as a command for the surface's root.
213pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
214    Action::Command(ROOT_ID, Command::SetStatusBar(patch))
215}
216
217struct Entry {
218    host: NodeId,
219    /// Out while it is polled.
220    future: Option<LocalFuture>,
221}
222
223#[derive(Default)]
224struct Inner {
225    tasks: FxHashMap<u64, Entry>,
226    next_task: u64,
227    actions: VecDeque<Action>,
228    failures: Vec<(NodeId, String)>,
229}
230
231/// The executor of one core's component tasks.
232#[derive(Default)]
233pub(crate) struct Executor {
234    inner: RefCell<Inner>,
235    ready: Arc<Ready>,
236    /// The runtime tasks are polled in the context of.
237    runtime: RefCell<Option<Handle>>,
238    /// Native animation nodes and animations made so far (their ids are
239    /// odd: JS's are even).
240    animation_ids: std::cell::Cell<u32>,
241    /// Live derived nodes, for what derives them again (a region or a row
242    /// made again).
243    derived: RefCell<super::animated::Derived>,
244    /// The components' listeners of the back button.
245    pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
246    /// The views' keyboard shortcuts.
247    pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
248    /// The timers tasks wait for ([`super::timer`]), soonest first: the core
249    /// fires them as they come due, and the engine's loop wakes for the
250    /// soonest, as it does for JS's timers.
251    timers: RefCell<BinaryHeap<Reverse<Timer>>>,
252    next_timer_seq: std::cell::Cell<u64>,
253}
254
255/// A task's timer: when, and whom to wake (in the order they were made
256/// among timers due at once).
257struct Timer {
258    at: Instant,
259    seq: u64,
260    waker: Waker,
261}
262
263impl PartialEq for Timer {
264    fn eq(&self, other: &Self) -> bool {
265        (self.at, self.seq) == (other.at, other.seq)
266    }
267}
268
269impl Eq for Timer {}
270
271impl PartialOrd for Timer {
272    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
273        Some(self.cmp(other))
274    }
275}
276
277impl Ord for Timer {
278    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
279        (self.at, self.seq).cmp(&(other.at, other.seq))
280    }
281}
282
283impl Executor {
284    /// The derived nodes and their handles.
285    pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
286        self.derived.borrow_mut()
287    }
288
289    /// Wakes `waker` at `at`.
290    pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
291        let seq = self.next_timer_seq.get();
292        self.next_timer_seq.set(seq + 1);
293        self.timers
294            .borrow_mut()
295            .push(Reverse(Timer { at, seq, waker }));
296    }
297
298    /// When the soonest timer is due.
299    pub(crate) fn next_timer(&self) -> Option<Instant> {
300        self.timers.borrow().peek().map(|Reverse(t)| t.at)
301    }
302
303    /// Wakes the timers due at `now`.
304    pub(crate) fn fire_timers(&self, now: Instant) {
305        let mut due = Vec::new();
306        {
307            let mut timers = self.timers.borrow_mut();
308            while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
309                if let Some(Reverse(timer)) = timers.pop() {
310                    due.push(timer.waker);
311                }
312            }
313        }
314        for waker in due {
315            waker.wake();
316        }
317    }
318
319    /// A new id for a native animation node or animation.
320    pub(crate) fn next_animation_id(&self) -> u32 {
321        let n = self.animation_ids.get();
322        self.animation_ids.set(n + 1);
323        2 * n + 1
324    }
325
326    pub(crate) fn set_runtime(&self, runtime: Handle) {
327        *self.runtime.borrow_mut() = Some(runtime);
328    }
329
330    pub(crate) fn set_notify(&self, notify: Notify) {
331        *self.ready.notify.lock().expect("notify lock") = Some(notify);
332    }
333
334    fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
335        let id = {
336            let mut inner = self.inner.borrow_mut();
337            inner.next_task += 1;
338            let id = inner.next_task;
339            inner.tasks.insert(
340                id,
341                Entry {
342                    host,
343                    future: Some(future),
344                },
345            );
346            id
347        };
348        // Polled at the next run, not inside the code that spawned it.
349        self.ready.ids.lock().expect("ready lock").push(id);
350        let notify = self.ready.notify.lock().expect("notify lock").clone();
351        if let Some(notify) = notify {
352            notify();
353        }
354        id
355    }
356
357    fn cancel(&self, id: u64) {
358        let removed = self.inner.borrow_mut().tasks.remove(&id);
359        // Dropped outside the borrow: the future may own other tasks.
360        drop(removed);
361    }
362
363    /// Polls the woken tasks; returns whether there were any.
364    pub(crate) fn poll_ready(&self) -> bool {
365        let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
366        if ids.is_empty() {
367            return false;
368        }
369        ids.sort_unstable();
370        ids.dedup();
371        // tokio's timers, IO and `spawn` find their runtime here.
372        let runtime = self.runtime.borrow().clone();
373        let _context = runtime.as_ref().map(Handle::enter);
374        for id in ids {
375            let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
376                Some(entry) => entry.future.take(),
377                None => None,
378            };
379            let Some(mut future) = future else { continue };
380            let waker = Waker::from(Arc::new(TaskWaker {
381                id,
382                ready: self.ready.clone(),
383            }));
384            let done = match super::component::caught(|| {
385                future
386                    .as_mut()
387                    .poll(&mut TaskContext::from_waker(&waker))
388                    .is_ready()
389            }) {
390                Ok(done) => done,
391                // A task that panicked ends; its component failed.
392                Err(message) => {
393                    let mut inner = self.inner.borrow_mut();
394                    if let Some(entry) = inner.tasks.get(&id) {
395                        let host = entry.host;
396                        inner.failures.push((host, message));
397                    }
398                    true
399                }
400            };
401            if done {
402                self.inner.borrow_mut().tasks.remove(&id);
403                drop(future);
404            } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
405                entry.future = Some(future);
406            }
407        }
408        true
409    }
410
411    #[cfg(test)]
412    pub(crate) fn task_count(&self) -> usize {
413        self.inner.borrow().tasks.len()
414    }
415
416    /// The tasks that panicked since, by component.
417    pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
418        std::mem::take(&mut self.inner.borrow_mut().failures)
419    }
420
421    /// What tasks asked of the platform.
422    pub(crate) fn take_actions(&self) -> VecDeque<Action> {
423        std::mem::take(&mut self.inner.borrow_mut().actions)
424    }
425
426    pub(crate) fn act(&self, action: Action) {
427        self.inner.borrow_mut().actions.push_back(action);
428        let notify = self.ready.notify.lock().expect("notify lock").clone();
429        if let Some(notify) = notify {
430            notify();
431        }
432    }
433}
434
435/// A running task of the core. Dropping it cancels the
436/// task (TS's `clearTimeout`, for timers); [`Task::detach`] lets it run
437/// on its own. Awaited in another task, it gives the task's output.
438#[must_use = "a dropped task is cancelled: keep it, or detach it"]
439pub struct Task<T> {
440    executor: Weak<Executor>,
441    id: u64,
442    output: Rc<RefCell<Output<T>>>,
443    detached: bool,
444}
445
446/// A value a future waits for, and the waker to call when it comes.
447pub(crate) struct Output<T> {
448    pub(crate) value: Option<T>,
449    pub(crate) waker: Option<Waker>,
450}
451
452/// Where an [`Answer`] comes from.
453pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
454
455impl<T> Default for Output<T> {
456    fn default() -> Self {
457        Self {
458            value: None,
459            waker: None,
460        }
461    }
462}
463
464impl<T> Output<T> {
465    /// Delivers `value`, waking the future waiting for it.
466    pub(crate) fn deliver(&mut self, value: T) {
467        self.value = Some(value);
468        if let Some(waker) = self.waker.take() {
469            waker.wake();
470        }
471    }
472}
473
474/// The answer the platform gives to a request (a dialog, an image's size),
475/// awaited in a task.
476#[must_use = "an answer does nothing unless awaited"]
477pub struct Answer<T> {
478    slot: Rc<RefCell<Output<T>>>,
479}
480
481/// The answer to a dialog (`nsh_base::alert_dialog`): the index of the
482/// button pressed, -1 when it was dismissed.
483pub type DialogAnswer = Answer<i32>;
484
485impl<T> Answer<T> {
486    pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
487        let slot = Rc::new(RefCell::new(Output::default()));
488        (Self { slot: slot.clone() }, slot)
489    }
490}
491
492impl<T> std::fmt::Debug for Answer<T> {
493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        f.debug_struct("Answer").finish_non_exhaustive()
495    }
496}
497
498impl<T> Future for Answer<T> {
499    type Output = T;
500
501    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
502        let mut slot = self.slot.borrow_mut();
503        match slot.value.take() {
504            Some(value) => Poll::Ready(value),
505            None => {
506                slot.waker = Some(cx.waker().clone());
507                Poll::Pending
508            }
509        }
510    }
511}
512
513impl<T> std::fmt::Debug for Task<T> {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        f.debug_struct("Task")
516            .field("id", &self.id)
517            .finish_non_exhaustive()
518    }
519}
520
521impl<T> Task<T> {
522    /// Lets the task run to its end without this handle (it still ends
523    /// with its component).
524    pub fn detach(mut self) {
525        self.detached = true;
526    }
527}
528
529impl<T> Drop for Task<T> {
530    fn drop(&mut self) {
531        if !self.detached
532            && let Some(executor) = self.executor.upgrade()
533        {
534            executor.cancel(self.id);
535        }
536    }
537}
538
539impl<T> Future for Task<T> {
540    type Output = T;
541
542    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
543        let mut output = self.output.borrow_mut();
544        match output.value.take() {
545            Some(value) => Poll::Ready(value),
546            None => {
547                output.waker = Some(cx.waker().clone());
548                Poll::Pending
549            }
550        }
551    }
552}
553
554/// Starts `future` as a task of `host`, to run to its end.
555pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
556    executor.spawn(host, future)
557}
558
559/// Applies `action` after `delay`, as a task of `host` (dropping the task
560/// cancels it).
561pub(crate) fn act_after(
562    executor: &Rc<Executor>,
563    host: NodeId,
564    delay: Duration,
565    action: Action,
566) -> Task<()> {
567    let weak = Rc::downgrade(executor);
568    let acting = weak.clone();
569    // From now, not from when the task is first polled.
570    let at = crate::time::now() + delay;
571    let id = executor.spawn(
572        host,
573        Box::pin(async move {
574            super::ambient::timer_until(at).await;
575            if let Some(executor) = acting.upgrade() {
576                executor.act(action);
577            }
578        }),
579    );
580    Task {
581        executor: weak,
582        id,
583        output: Rc::new(RefCell::new(Output::default())),
584        detached: false,
585    }
586}
587
588/// Starts `future` on the engine thread, with no component (a task of a
589/// component that runs once: its owner ends it, [`TaskHandle::cancel`]).
590/// The task is detached: dropping it does not cancel it.
591pub(crate) fn spawn_future<R: 'static>(
592    executor: &Rc<Executor>,
593    future: impl Future<Output = R> + 'static,
594) -> Task<R> {
595    let weak = Rc::downgrade(executor);
596    let output = Rc::new(RefCell::new(Output {
597        value: None,
598        waker: None,
599    }));
600    let done = output.clone();
601    let id = executor.spawn(
602        0,
603        Box::pin(async move {
604            let value = future.await;
605            let mut output = done.borrow_mut();
606            output.value = Some(value);
607            if let Some(waker) = output.waker.take() {
608                waker.wake();
609            }
610        }),
611    );
612    Task {
613        executor: weak,
614        id,
615        output,
616        detached: true,
617    }
618}
619
620/// What cancels a task, apart from its handle.
621pub(crate) struct TaskHandle {
622    executor: Weak<Executor>,
623    id: u64,
624}
625
626impl TaskHandle {
627    /// Ends the task (nothing when it ended already).
628    pub(crate) fn cancel(&self) {
629        if let Some(executor) = self.executor.upgrade() {
630            executor.cancel(self.id);
631        }
632    }
633}
634
635impl<T> Task<T> {
636    /// What cancels it.
637    pub(crate) fn handle(&self) -> TaskHandle {
638        TaskHandle {
639            executor: self.executor.clone(),
640            id: self.id,
641        }
642    }
643}