Skip to main content

nsh_core/element/
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}
137
138/// What the core hands JS after a commit, in order: the platform's and the
139/// core's events, and the Rust values for JS (a Rust component's events,
140/// whether its lazy children are placed, calls' results).
141pub enum JsEvent {
142    /// An event of a node (layout, scroll, a platform component's).
143    Event(NodeId, EventKind, EventPayload),
144    /// The initial frame for one newly installed Rust layout listener.
145    /// Delivered by the engine to `Core::component_layout`.
146    #[doc(hidden)]
147    LayoutListener {
148        /// The component whose view installed the listener.
149        host: NodeId,
150        /// Its node.
151        id: NodeId,
152        /// The newly installed callback.
153        listener: super::Listener<EventPayload>,
154        /// The node's current frame.
155        frame: crate::Bounds<crate::Points>,
156    },
157    /// An event of the Rust component hosted by `host`.
158    Component {
159        /// The component's host node.
160        host: NodeId,
161        /// The event.
162        event: Box<dyn EventToJs>,
163    },
164    /// Whether the Rust component hosted by `host` places its lazy
165    /// children now.
166    Children {
167        /// The component's host node.
168        host: NodeId,
169        /// Placed.
170        wanted: bool,
171    },
172    /// The Rust component hosted by `host` places the content of its
173    /// render prop `prop` (`Option<Renderer<T>>`) for `key` with `value`,
174    /// which JS did not render yet: JS calls the app's function with it
175    /// and inserts what it returns into the host in a holder view of its
176    /// own (`componentRender`: the prop, U+001F, the key), replacing the
177    /// one it made for the key before. The core places the holder.
178    Render {
179        /// The component's host node.
180        host: NodeId,
181        /// The prop holding the app's function.
182        prop: &'static str,
183        /// The key, unique among the component's renders of the prop.
184        key: super::SharedString,
185        /// The value to render.
186        value: std::rc::Rc<dyn super::RenderValue>,
187        /// The function to render with instead of the prop's, which the
188        /// component holds itself: JS calls it once for the key, with
189        /// props reading the latest value, and a later `Render` of the key
190        /// sets that value in place (no new holder).
191        func: Option<std::rc::Rc<dyn super::CallbackHandle>>,
192    },
193    /// No element of the component's render (`prop`, `key`) is placed any
194    /// more ([`Self::Render`]): JS removes its holder and disposes what it
195    /// rendered.
196    Unrender {
197        /// The component's host node.
198        host: NodeId,
199        /// The prop holding the app's function.
200        prop: &'static str,
201        /// The key.
202        key: super::SharedString,
203    },
204    /// The `<Each>` rows whose placeholders ([`crate::Op::Placeholder`])
205    /// would be made now: JS renders them in their place.
206    #[doc(hidden)]
207    Rows(Vec<NodeId>),
208    /// The result of call `call` (its promise settles).
209    Reply {
210        /// The call number.
211        call: u32,
212        /// The value or the rejection's message.
213        result: JsResult,
214    },
215}
216
217impl fmt::Debug for JsEvent {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        match self {
220            JsEvent::Event(id, kind, payload) => write!(f, "Event({id}, {kind:?}, {payload:?})"),
221            JsEvent::LayoutListener {
222                host, id, frame, ..
223            } => {
224                write!(f, "LayoutListener({host}, {id}, {frame:?})")
225            }
226            JsEvent::Component { host, event } => write!(f, "Component({host}, {})", event.name()),
227            JsEvent::Children { host, wanted } => write!(f, "Children({host}, {wanted})"),
228            JsEvent::Render {
229                host, prop, key, ..
230            } => write!(f, "Render({host}, {prop}, {key})"),
231            JsEvent::Unrender { host, prop, key } => write!(f, "Unrender({host}, {prop}, {key})"),
232            JsEvent::Rows(ids) => write!(f, "Rows({ids:?})"),
233            JsEvent::Reply { call, result } => write!(f, "Reply({call}, ok: {})", result.is_ok()),
234        }
235    }
236}
237
238// --- Posts ----------------------------------------------------------------------
239
240/// The place in [`Posts`] of a call posted during a synchronous call from
241/// JS, which [`RustCall::Post`] carries: dropping it lets the call run
242/// there, whichever path drops it (the op applied, or dropped unapplied).
243#[doc(hidden)]
244pub struct ParkedPost {
245    posts: Posts,
246    id: u64,
247}
248
249impl Drop for ParkedPost {
250    fn drop(&mut self) {
251        self.posts.release(self.id);
252    }
253}
254
255impl fmt::Debug for ParkedPost {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        write!(f, "ParkedPost({})", self.id)
258    }
259}
260
261/// The calls of JS functions Rust posts ([`super::Callback::post`],
262/// `call_async`) for the next JS turn, in one ordered queue. One per
263/// engine, made by it and handed to `nsh-js` and the core. Cheap to clone.
264///
265/// The calls run in the order they were posted, with one exception that
266/// keeps JS's program order: a call posted during a synchronous call from
267/// JS is parked in its place until the op JS sent after it is applied
268/// ([`RustCall::Post`]), and what the ops before that one post while the
269/// core applies them goes before it. So a call a task posts after the
270/// synchronous call runs after it, and one an op JS sent before the call
271/// posts runs before it. The queue runs up to the first place not
272/// released yet; a place is released whichever way its op goes (applied,
273/// or dropped unapplied: [`ParkedPost`]), so no lost op stalls it.
274#[derive(Clone, Default)]
275pub struct Posts(Rc<PostsInner>);
276
277#[derive(Default)]
278struct PostsInner {
279    queue: RefCell<VecDeque<Entry>>,
280    next_parked: Cell<u64>,
281    /// The core is applying an op JS sent ([`Posts::in_op`]).
282    in_op: Cell<u32>,
283    notify: RefCell<Option<Arc<dyn Fn() + Send + Sync>>>,
284    /// JS stopped for good: calls are dropped (their replies say so).
285    closed: Cell<bool>,
286}
287
288enum Entry {
289    Ready(JsCall),
290    /// Parked as `id`; released (runnable) once its op goes.
291    Parked {
292        id: u64,
293        call: JsCall,
294        released: bool,
295    },
296}
297
298impl fmt::Debug for Posts {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.debug_struct("Posts")
301            .field("queued", &self.0.queue.borrow().len())
302            .finish()
303    }
304}
305
306impl Posts {
307    /// An empty queue.
308    pub fn new() -> Self {
309        Self::default()
310    }
311
312    /// Calls `notify` when a call becomes runnable (it wakes the engine).
313    pub fn set_notify(&self, notify: Arc<dyn Fn() + Send + Sync>) {
314        *self.0.notify.borrow_mut() = Some(notify);
315    }
316
317    fn wake(&self) {
318        let notify = self.0.notify.borrow().clone();
319        if let Some(notify) = notify {
320            notify();
321        }
322    }
323
324    /// Queues `call` and wakes the engine.
325    #[doc(hidden)]
326    pub fn post(&self, call: JsCall) {
327        if self.0.closed.get() {
328            // Dropped: a reply waiting for it is told JS stopped.
329            drop(call);
330            return;
331        }
332        {
333            let mut queue = self.0.queue.borrow_mut();
334            // An op's post goes before the places of the calls JS posted
335            // after sending it (parked, not released: their ops come
336            // later).
337            let at = (self.0.in_op.get() > 0)
338                .then(|| {
339                    queue.iter().position(|e| {
340                        matches!(
341                            e,
342                            Entry::Parked {
343                                released: false,
344                                ..
345                            }
346                        )
347                    })
348                })
349                .flatten();
350            match at {
351                Some(at) => queue.insert(at, Entry::Ready(call)),
352                None => queue.push_back(Entry::Ready(call)),
353            }
354        }
355        self.wake();
356    }
357
358    /// Runs `f`, the work of an op JS sent: what it posts goes before the
359    /// calls JS posted after the op.
360    pub(crate) fn in_op<R>(&self, f: impl FnOnce() -> R) -> R {
361        struct Raised<'a>(&'a Cell<u32>);
362        impl Drop for Raised<'_> {
363            fn drop(&mut self) {
364                self.0.set(self.0.get() - 1);
365            }
366        }
367        self.0.in_op.set(self.0.in_op.get() + 1);
368        let _raised = Raised(&self.0.in_op);
369        f()
370    }
371
372    /// Queues `call` parked in its place until the place it returns is
373    /// dropped: when its op is applied, or dropped by any other path (the
374    /// call then runs in its place, or with the queue when it closes), so
375    /// a lost op never holds back the calls after it.
376    #[doc(hidden)]
377    pub fn park(&self, call: JsCall) -> ParkedPost {
378        let id = self.0.next_parked.get() + 1;
379        self.0.next_parked.set(id);
380        if self.0.closed.get() {
381            drop(call);
382        } else {
383            self.0.queue.borrow_mut().push_back(Entry::Parked {
384                id,
385                call,
386                released: false,
387            });
388        }
389        ParkedPost {
390            posts: self.clone(),
391            id,
392        }
393    }
394
395    /// Lets the call parked as `id` run in its place.
396    fn release(&self, id: u64) {
397        let found = self.0.queue.borrow_mut().iter_mut().any(|e| match e {
398            Entry::Parked {
399                id: parked,
400                released,
401                ..
402            } if *parked == id => {
403                *released = true;
404                true
405            }
406            _ => false,
407        });
408        if found {
409            self.wake();
410        }
411    }
412
413    /// No JS runs any more (the VM stopped or went): the queued calls are
414    /// dropped, and so are those posted later (their replies say so).
415    pub fn close(&self) {
416        self.0.closed.set(true);
417        let queue = std::mem::take(&mut *self.0.queue.borrow_mut());
418        drop(queue);
419    }
420
421    /// Whether a call can run now.
422    pub fn has_calls(&self) -> bool {
423        matches!(
424            self.0.queue.borrow().front(),
425            Some(Entry::Ready(_) | Entry::Parked { released: true, .. })
426        )
427    }
428
429    /// The calls that can run now, in order: up to the first parked one not
430    /// released yet.
431    #[doc(hidden)]
432    pub fn take_calls(&self) -> Vec<JsCall> {
433        let mut queue = self.0.queue.borrow_mut();
434        let mut out = Vec::new();
435        while let Some(entry) = queue.front() {
436            if matches!(
437                entry,
438                Entry::Parked {
439                    released: false,
440                    ..
441                }
442            ) {
443                break;
444            }
445            match queue.pop_front() {
446                Some(Entry::Ready(call) | Entry::Parked { call, .. }) => out.push(call),
447                None => break,
448            }
449        }
450        out
451    }
452}