Skip to main content

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