Skip to main content

nsh_core/ui/
call.rs

1//! Calls from JS into Rust, and what goes back, as Rust values: no JSON
2//! between JS and Rust components, modules or classes.
3//!
4//! `nsh-js` converts a call's JS arguments into the Rust types in the JS
5//! call (the generated decoders, [`super::JsValue::from_js`]) and queues
6//! what the call does as an op ([`RustOp`]): a closure holding the typed
7//! arguments, which the core runs in order with the UI's ops (a module
8//! function with a [`super::ModuleCx`], the start of an `async` function's
9//! or member's task, a ref's method). Results are boxed Rust values
10//! ([`ToJs`]) the core hands back in its event stream ([`JsEvent`]), in
11//! order with the other events, and `nsh-js` converts them when it settles
12//! the promise. A Rust component's props cross the same way: decoded in
13//! the JS call into an [`AnyValue`], set by the core.
14//!
15//! Platform native components (the components an embedder registers in
16//! its own language) keep JSON (`Prop::ComponentProp`, `EventPayload::Native`,
17//! `Command::Native`): their values cross into another language.
18
19use std::{
20    any::Any,
21    cell::{Cell, RefCell},
22    collections::VecDeque,
23    fmt,
24    rc::Rc,
25    sync::Arc,
26};
27
28use super::{
29    ModuleCx, ModuleFuture, PropError,
30    callback::JsCall,
31    js::{JsHost, JsOwned},
32};
33use crate::{EventKind, EventPayload, NodeId};
34
35/// A Rust value of some type, decoded from JS for a component's prop.
36/// Cheap to clone; two are equal when they are the same value (the prop
37/// keeps its own comparison of what it holds).
38#[derive(Clone)]
39pub struct AnyValue(Rc<dyn Any>);
40
41impl AnyValue {
42    /// `value`, type-erased.
43    pub fn new<T: 'static>(value: T) -> Self {
44        Self(Rc::new(value))
45    }
46
47    /// The value, if it is a `T`.
48    pub fn take<T: Clone + 'static>(self) -> Option<T> {
49        self.0.downcast::<T>().ok().map(Rc::unwrap_or_clone)
50    }
51}
52
53impl PartialEq for AnyValue {
54    fn eq(&self, other: &Self) -> bool {
55        Rc::ptr_eq(&self.0, &other.0)
56    }
57}
58
59impl fmt::Debug for AnyValue {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str("AnyValue")
62    }
63}
64
65/// A Rust value JS gets: converted when JS receives it (a call's result,
66/// an event's data).
67pub trait ToJs: 'static {
68    /// The value as a JS value of `host`.
69    fn to_js_value<'a>(self: Box<Self>, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
70}
71
72impl<T: super::Ret + 'static> ToJs for T {
73    fn to_js_value<'a>(self: Box<Self>, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
74        (*self).into_js(host)
75    }
76}
77
78/// The result of a call JS waits for: the value, or the message its
79/// promise rejects with.
80pub type JsResult = Result<Box<dyn ToJs>, super::Thrown>;
81
82/// A module function with a context, its arguments decoded: run by the
83/// core in order with the UI's ops.
84pub type OpCall = Box<dyn FnOnce(&mut ModuleCx) -> JsResult>;
85
86/// The start of an `async` function's or member's task, its arguments
87/// decoded: the core starts it in order with the UI's ops.
88pub type TaskStart = Box<dyn FnOnce() -> ModuleFuture>;
89
90/// A method of a component's ref, its arguments decoded: called with the
91/// API the component registered (`None`: an API of another type).
92pub type MethodCall = Box<dyn FnOnce(&dyn Any) -> Option<JsResult>>;
93
94/// What a call JS made into Rust does, carried by an op.
95pub enum RustCall {
96    /// A module function with a context.
97    Op(OpCall),
98    /// The start of an `async` function's or member's task.
99    Task(TaskStart),
100    /// A method of the ref of the component on node `0`.
101    Method(NodeId, MethodCall),
102    /// The place of a JS call posted during a synchronous call from JS
103    /// ([`Posts::park`]): applied (dropped), the call runs after what the
104    /// ops before it post.
105    Post(ParkedPost),
106}
107
108/// A call JS made into Rust ([`crate::Op::Rust`]): what it does, and the
109/// number of the promise its result settles (0: none).
110pub struct RustOp {
111    /// The promise's call number (0: JS does not wait).
112    pub call: u32,
113    /// What it does.
114    pub run: RustCall,
115}
116
117impl fmt::Debug for RustOp {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        let kind = match &self.run {
120            RustCall::Op(_) => "Op",
121            RustCall::Task(_) => "Task",
122            RustCall::Method(..) => "Method",
123            RustCall::Post(_) => "Post",
124        };
125        write!(f, "RustOp({kind}, call {})", self.call)
126    }
127}
128
129/// A Rust component's event JS hears: its name and data.
130#[doc(hidden)]
131pub trait EventToJs {
132    /// The event's name (`press`: JS's `onPress`).
133    fn name(&self) -> &'static str;
134    /// Its data as a JS value of `host`.
135    fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
136    /// The handler takes the items of the data as its arguments.
137    fn spread(&self) -> bool {
138        false
139    }
140}
141
142/// What the core hands JS after a commit, in order: the platform's and the
143/// core's events, and the Rust values for JS (a Rust component's events,
144/// whether its lazy children are placed, calls' results).
145pub enum JsEvent {
146    /// An event of a node (layout, scroll, a platform component's).
147    Event(NodeId, EventKind, EventPayload),
148    /// An event of the Rust component hosted by `host`.
149    Component {
150        /// The component's host node.
151        host: NodeId,
152        /// The event.
153        event: Box<dyn EventToJs>,
154    },
155    /// Whether the Rust component hosted by `host` places its lazy
156    /// children now.
157    Children {
158        /// The component's host node.
159        host: NodeId,
160        /// Placed.
161        wanted: bool,
162    },
163    /// The Rust component hosted by `host` places the content of its
164    /// render prop `prop` (`Option<Renderer<T>>`) for `key` with `value`,
165    /// which JS did not render yet: JS calls the app's function with it
166    /// and inserts what it returns into the host in a holder view of its
167    /// own (`componentRender`: the prop, U+001F, the key), replacing the
168    /// one it made for the key before. The core places the holder.
169    Render {
170        /// The component's host node.
171        host: NodeId,
172        /// The prop holding the app's function.
173        prop: &'static str,
174        /// The key, unique among the component's renders of the prop.
175        key: super::SharedString,
176        /// The value to render.
177        value: std::rc::Rc<dyn super::RenderValue>,
178    },
179    /// No element of the component's render (`prop`, `key`) is placed any
180    /// more ([`Self::Render`]): JS removes its holder and disposes what it
181    /// rendered.
182    Unrender {
183        /// The component's host node.
184        host: NodeId,
185        /// The prop holding the app's function.
186        prop: &'static str,
187        /// The key.
188        key: super::SharedString,
189    },
190    /// The result of call `call` (its promise settles).
191    Reply {
192        /// The call number.
193        call: u32,
194        /// The value or the rejection's message.
195        result: JsResult,
196    },
197}
198
199impl fmt::Debug for JsEvent {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        match self {
202            JsEvent::Event(id, kind, payload) => write!(f, "Event({id}, {kind:?}, {payload:?})"),
203            JsEvent::Component { host, event } => write!(f, "Component({host}, {})", event.name()),
204            JsEvent::Children { host, wanted } => write!(f, "Children({host}, {wanted})"),
205            JsEvent::Render {
206                host, prop, key, ..
207            } => write!(f, "Render({host}, {prop}, {key})"),
208            JsEvent::Unrender { host, prop, key } => write!(f, "Unrender({host}, {prop}, {key})"),
209            JsEvent::Reply { call, result } => write!(f, "Reply({call}, ok: {})", result.is_ok()),
210        }
211    }
212}
213
214// --- Posts ----------------------------------------------------------------------
215
216/// The place in [`Posts`] of a call posted during a synchronous call from
217/// JS, which [`RustCall::Post`] carries: dropping it lets the call run
218/// there, whichever path drops it (the op applied, or dropped unapplied).
219#[doc(hidden)]
220pub struct ParkedPost {
221    posts: Posts,
222    id: u64,
223}
224
225impl Drop for ParkedPost {
226    fn drop(&mut self) {
227        self.posts.release(self.id);
228    }
229}
230
231impl fmt::Debug for ParkedPost {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        write!(f, "ParkedPost({})", self.id)
234    }
235}
236
237/// The calls of JS functions Rust posts ([`super::Callback::post`],
238/// `call_async`) for the next JS turn, in one ordered queue. One per
239/// engine, made by it and handed to `nsh-js` and the core. Cheap to clone.
240///
241/// The calls run in the order they were posted, with one exception that
242/// keeps JS's program order: a call posted during a synchronous call from
243/// JS is parked in its place until the op JS sent after it is applied
244/// ([`RustCall::Post`]), and what the ops before that one post while the
245/// core applies them goes before it. So a call a task posts after the
246/// synchronous call runs after it, and one an op JS sent before the call
247/// posts runs before it. The queue runs up to the first place not
248/// released yet; a place is released whichever way its op goes (applied,
249/// or dropped unapplied: [`ParkedPost`]), so no lost op stalls it.
250#[derive(Clone, Default)]
251pub struct Posts(Rc<PostsInner>);
252
253#[derive(Default)]
254struct PostsInner {
255    queue: RefCell<VecDeque<Entry>>,
256    next_parked: Cell<u64>,
257    /// The core is applying an op JS sent ([`Posts::in_op`]).
258    in_op: Cell<u32>,
259    notify: RefCell<Option<Arc<dyn Fn() + Send + Sync>>>,
260    /// JS stopped for good: calls are dropped (their replies say so).
261    closed: Cell<bool>,
262}
263
264enum Entry {
265    Ready(JsCall),
266    /// Parked as `id`; released (runnable) once its op goes.
267    Parked {
268        id: u64,
269        call: JsCall,
270        released: bool,
271    },
272}
273
274impl fmt::Debug for Posts {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        f.debug_struct("Posts")
277            .field("queued", &self.0.queue.borrow().len())
278            .finish()
279    }
280}
281
282impl Posts {
283    /// An empty queue.
284    pub fn new() -> Self {
285        Self::default()
286    }
287
288    /// Calls `notify` when a call becomes runnable (it wakes the engine).
289    pub fn set_notify(&self, notify: Arc<dyn Fn() + Send + Sync>) {
290        *self.0.notify.borrow_mut() = Some(notify);
291    }
292
293    fn wake(&self) {
294        let notify = self.0.notify.borrow().clone();
295        if let Some(notify) = notify {
296            notify();
297        }
298    }
299
300    /// Queues `call` and wakes the engine.
301    #[doc(hidden)]
302    pub fn post(&self, call: JsCall) {
303        if self.0.closed.get() {
304            // Dropped: a reply waiting for it is told JS stopped.
305            drop(call);
306            return;
307        }
308        {
309            let mut queue = self.0.queue.borrow_mut();
310            // An op's post goes before the places of the calls JS posted
311            // after sending it (parked, not released: their ops come
312            // later).
313            let at = (self.0.in_op.get() > 0)
314                .then(|| {
315                    queue.iter().position(|e| {
316                        matches!(
317                            e,
318                            Entry::Parked {
319                                released: false,
320                                ..
321                            }
322                        )
323                    })
324                })
325                .flatten();
326            match at {
327                Some(at) => queue.insert(at, Entry::Ready(call)),
328                None => queue.push_back(Entry::Ready(call)),
329            }
330        }
331        self.wake();
332    }
333
334    /// Runs `f`, the work of an op JS sent: what it posts goes before the
335    /// calls JS posted after the op.
336    pub(crate) fn in_op<R>(&self, f: impl FnOnce() -> R) -> R {
337        struct Raised<'a>(&'a Cell<u32>);
338        impl Drop for Raised<'_> {
339            fn drop(&mut self) {
340                self.0.set(self.0.get() - 1);
341            }
342        }
343        self.0.in_op.set(self.0.in_op.get() + 1);
344        let _raised = Raised(&self.0.in_op);
345        f()
346    }
347
348    /// Queues `call` parked in its place until the place it returns is
349    /// dropped: when its op is applied, or dropped by any other path (the
350    /// call then runs in its place, or with the queue when it closes), so
351    /// a lost op never holds back the calls after it.
352    #[doc(hidden)]
353    pub fn park(&self, call: JsCall) -> ParkedPost {
354        let id = self.0.next_parked.get() + 1;
355        self.0.next_parked.set(id);
356        if self.0.closed.get() {
357            drop(call);
358        } else {
359            self.0.queue.borrow_mut().push_back(Entry::Parked {
360                id,
361                call,
362                released: false,
363            });
364        }
365        ParkedPost {
366            posts: self.clone(),
367            id,
368        }
369    }
370
371    /// Lets the call parked as `id` run in its place.
372    fn release(&self, id: u64) {
373        let found = self.0.queue.borrow_mut().iter_mut().any(|e| match e {
374            Entry::Parked {
375                id: parked,
376                released,
377                ..
378            } if *parked == id => {
379                *released = true;
380                true
381            }
382            _ => false,
383        });
384        if found {
385            self.wake();
386        }
387    }
388
389    /// No JS runs any more (the VM stopped or went): the queued calls are
390    /// dropped, and so are those posted later (their replies say so).
391    pub fn close(&self) {
392        self.0.closed.set(true);
393        let queue = std::mem::take(&mut *self.0.queue.borrow_mut());
394        drop(queue);
395    }
396
397    /// Whether a call can run now.
398    pub fn has_calls(&self) -> bool {
399        matches!(
400            self.0.queue.borrow().front(),
401            Some(Entry::Ready(_) | Entry::Parked { released: true, .. })
402        )
403    }
404
405    /// The calls that can run now, in order: up to the first parked one not
406    /// released yet.
407    #[doc(hidden)]
408    pub fn take_calls(&self) -> Vec<JsCall> {
409        let mut queue = self.0.queue.borrow_mut();
410        let mut out = Vec::new();
411        while let Some(entry) = queue.front() {
412            if matches!(
413                entry,
414                Entry::Parked {
415                    released: false,
416                    ..
417                }
418            ) {
419                break;
420            }
421            match queue.pop_front() {
422                Some(Entry::Ready(call) | Entry::Parked { call, .. }) => out.push(call),
423                None => break,
424            }
425        }
426        out
427    }
428}