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