Skip to main content

nsh_engine/
lib.rs

1//! The engine thread of one surface.
2//!
3//! The engine owns a [`nsh_core::Core`] on a dedicated thread and runs one
4//! app ([`App`]): a Rust app's root component, or a JS bundle in a QuickJS
5//! VM (`nsh_js::Host`, feature `js`). Each wake-up (input event, timer,
6//! resize) runs the app's code (component tasks; JS and its microtasks),
7//! applies what JS committed, lays out, and hands one [`MountBatch`] to the
8//! platform through a [`MountSink`]. The platform thread never blocks on
9//! the engine.
10
11mod access;
12pub mod perf;
13mod script;
14#[cfg(feature = "js")]
15mod symbolicate;
16
17use std::{io, rc::Rc, sync::Arc, time::Duration};
18
19use crossbeam_channel::{Receiver, Sender};
20use nsh_core::{
21    ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
22    PayloadValue, Size, TextEngine, time::Instant,
23};
24pub use nsh_core::{
25    access::{Access, Capabilities},
26    js::Limits,
27    platform::{
28        ColorScheme, Environment, FetchEvent, FetchOp, HttpBody, HttpHead, HttpRequest, Idiom,
29        Insets, Locale, Os,
30    },
31    ui::{Root, Theme},
32};
33#[cfg(feature = "js")]
34pub use nsh_js::BYTECODE_VERSION;
35/// Signed packages, release-key certificates, revocations and trust stores.
36#[cfg(feature = "js")]
37pub use nsh_package as package;
38use rustc_hash::FxHashMap;
39
40use crate::script::{NetworkQueue, RequestId, Script};
41
42#[cfg(not(target_arch = "wasm32"))]
43/// Stack size of the engine thread. QuickJS recursion (and deep Solid
44/// component trees) needs more than the 512 KiB default of secondary
45/// threads on Apple platforms.
46const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
47
48/// Minimum time between idle cycle collections. QuickJS frees acyclic
49/// garbage immediately; only cycles (such as detached node subtrees, whose
50/// parent/child links reference each other) wait for the collector.
51const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
52
53/// The app an engine runs.
54#[derive(Debug, Clone)]
55pub enum App {
56    /// A Rust app: its root component, mounted as the surface's content.
57    Rust(Root),
58    /// A JS app (feature `js`).
59    Js(Bundle),
60}
61
62impl From<Bundle> for App {
63    fn from(bundle: Bundle) -> Self {
64        App::Js(bundle)
65    }
66}
67
68impl From<Root> for App {
69    fn from(root: Root) -> Self {
70        App::Rust(root)
71    }
72}
73
74/// An app bundle: its code plus, in development, a source map.
75#[derive(Debug, Clone)]
76pub struct Bundle {
77    /// The code.
78    pub code: BundleCode,
79    /// Source map (JSON) used to show app source locations in stack traces.
80    pub source_map: Option<Arc<str>>,
81    /// What the code may do.
82    pub policy: Policy,
83    /// What relative request URLs resolve against (the page's URL on the
84    /// web); `None`: they are invalid.
85    pub base_url: Option<Arc<str>>,
86    /// The chunks of a split bundle that come with it (`import()` loads
87    /// them without asking the platform); those missing are asked of
88    /// [`MountSink::load_chunk`]. Shared by the bundle's clones.
89    pub chunks: Arc<Vec<Chunk>>,
90    /// The sandbox's hardening as bytecode (`nsh_js::compile_harden`),
91    /// for a runtime without QuickJS' parser (the web runtime of published
92    /// apps); `None`: compiled when the policy hardens. Set it with
93    /// [`Bundle::with_harden_bytecode`].
94    pub harden_bytecode: Option<Arc<Vec<u8>>>,
95}
96
97/// A chunk of a split bundle (`nsh_bundler::Chunk`): app code that
98/// `import()` loads on demand.
99#[derive(Debug, Clone)]
100pub struct Chunk {
101    /// Its id (`Screen.js`), as the bundle imports it.
102    pub id: String,
103    /// The code.
104    pub code: BundleCode,
105    /// Source map (JSON), for stack traces.
106    pub source_map: Option<Arc<str>>,
107}
108
109impl Chunk {
110    /// A chunk as JS source.
111    pub fn source(id: impl Into<String>, code: String) -> Self {
112        Self {
113            id: id.into(),
114            code: BundleCode::Source(code),
115            source_map: None,
116        }
117    }
118
119    /// A chunk as bytecode (`nsh_js::compile_chunk_bytecode`).
120    ///
121    /// # Safety
122    ///
123    /// As [`Bundle::bytecode`].
124    pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
125        Self {
126            id: id.into(),
127            code: BundleCode::Bytecode(bytes),
128            source_map: None,
129        }
130    }
131
132    /// Attaches a source map.
133    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
134        self.source_map = Some(map.into());
135        self
136    }
137}
138
139/// What a bundle's code may do.
140#[derive(Debug, Clone)]
141pub struct Policy {
142    /// Run without `eval`, the function constructors and writable shared
143    /// prototypes (see `nsh_js::HostOptions::harden`). On by default; off for
144    /// development bundles.
145    pub harden: bool,
146    /// What the app declared (`nsh.json` `capabilities`); `None`: no
147    /// declaration, everything.
148    pub declared: Option<Capabilities>,
149    /// What the embedding app grants at most; `None`: whatever the app
150    /// declared.
151    pub granted: Option<Capabilities>,
152}
153
154impl Default for Policy {
155    fn default() -> Self {
156        Self {
157            harden: true,
158            declared: None,
159            granted: None,
160        }
161    }
162}
163
164impl Policy {
165    /// Development bundles: `eval` and friends stay (debugging); the
166    /// capabilities are still enforced, so a missing one shows during
167    /// development.
168    pub fn development() -> Self {
169        Self {
170            harden: false,
171            ..Self::default()
172        }
173    }
174
175    /// What the app may reach under this policy.
176    pub fn access(&self) -> Access {
177        Access {
178            declared: self.declared.clone().unwrap_or_else(Capabilities::all),
179            granted: self.granted.clone(),
180        }
181    }
182}
183
184/// The code of a bundle.
185#[derive(Debug, Clone)]
186pub enum BundleCode {
187    /// QuickJS bytecode from `nsh_js::compile_bytecode`.
188    Bytecode(Vec<u8>),
189    /// JS source; slower to start than bytecode.
190    Source(String),
191}
192
193impl Bundle {
194    /// A bytecode bundle.
195    ///
196    /// # Safety
197    ///
198    /// `bytes` must be bytecode from `nsh_js::compile_bytecode` for this
199    /// runtime's `BYTECODE_VERSION`, from a trusted source: QuickJS does not
200    /// validate bytecode, and loading crafted bytecode corrupts memory. Trusted
201    /// are the app's own signed resources, a development server the developer
202    /// pointed the host at, and verified packages ([`Bundle::from_package`]).
203    pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
204        Self {
205            code: BundleCode::Bytecode(bytes),
206            source_map: None,
207            policy: Policy::default(),
208            base_url: None,
209            chunks: Arc::default(),
210            harden_bytecode: None,
211        }
212    }
213
214    /// A JS source bundle.
215    pub fn source(code: String) -> Self {
216        Self {
217            code: BundleCode::Source(code),
218            source_map: None,
219            policy: Policy::default(),
220            base_url: None,
221            chunks: Arc::default(),
222            harden_bytecode: None,
223        }
224    }
225
226    /// Attaches a source map.
227    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
228        self.source_map = Some(map.into());
229        self
230    }
231
232    /// Sets the URL relative request URLs resolve against.
233    pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
234        self.base_url = Some(url.into());
235        self
236    }
237
238    /// Hardens with `bytes` ([`Bundle::harden_bytecode`]).
239    ///
240    /// # Safety
241    ///
242    /// As [`Bundle::bytecode`]: `bytes` comes from `nsh_js::compile_harden`
243    /// of this runtime's `BYTECODE_VERSION`, from a trusted source.
244    pub unsafe fn with_harden_bytecode(mut self, bytes: Vec<u8>) -> Self {
245        self.harden_bytecode = Some(Arc::new(bytes));
246        self
247    }
248
249    /// Replaces the policy.
250    pub fn with_policy(mut self, policy: Policy) -> Self {
251        self.policy = policy;
252        self
253    }
254
255    /// Adds chunks of a split bundle (see [`Bundle::chunks`]).
256    pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
257        Arc::make_mut(&mut self.chunks).extend(chunks);
258        self
259    }
260
261    /// Reads a JS source bundle written by `nsh build` (`bundle.js`), plus
262    /// `bundle.js.map` and the app's `capabilities.json` next to it if
263    /// present. Bytecode (`bundle.nshc`) is refused: files can be replaced, and
264    /// only [`Bundle::read_trusted`] (the app's own resources) or a verified
265    /// package may load bytecode.
266    pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
267        if path.extension().is_some_and(|e| e == "nshc") {
268            return Err(io::Error::other(
269                "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
270            ));
271        }
272        // SAFETY: not bytecode.
273        unsafe { Self::read_trusted(path) }
274    }
275
276    /// Like [`Bundle::read`], also reading `bundle.nshc` as bytecode.
277    ///
278    /// # Safety
279    ///
280    /// A `.nshc` file must be trusted as [`Bundle::bytecode`] requires (e.g.
281    /// inside the app's own signed bundle).
282    pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
283        let bytes = std::fs::read(path)?;
284        let bundle = if path.extension().is_some_and(|e| e == "nshc") {
285            // SAFETY: guaranteed by the caller.
286            unsafe { Bundle::bytecode(bytes) }
287        } else {
288            Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
289        };
290        let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
291            Ok(map) if !map.is_empty() => bundle.with_source_map(map),
292            _ => bundle,
293        };
294        if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
295            bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
296        }
297        Ok(bundle)
298    }
299}
300
301#[cfg(feature = "js")]
302impl Bundle {
303    /// The bundle of a verified package: its bytecode when it was compiled
304    /// for this runtime (else its source), its source map and its declared
305    /// capabilities.
306    pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
307        let bundle = match package.bytecode() {
308            // SAFETY: verified: signed by a certified release key, hashed,
309            // and compiled for this runtime.
310            Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
311            None => Bundle::source(package.source.clone()),
312        };
313        let mut bundle = match &package.source_map {
314            Some(map) => bundle.with_source_map(map.clone()),
315            None => bundle,
316        };
317        bundle.policy.declared = package
318            .capabilities
319            .as_ref()
320            .map(Capabilities::from_json)
321            .transpose()?;
322        Ok(bundle)
323    }
324}
325
326/// A verified package, unpacked ([`load_package`]).
327#[cfg(feature = "js")]
328#[derive(Debug)]
329pub struct LoadedPackage {
330    /// Its bundle.
331    pub bundle: Bundle,
332    /// Where its assets are (`asset:/…`).
333    pub assets: std::path::PathBuf,
334    /// Its app.
335    pub app: nsh_package::App,
336}
337
338/// Verifies the package `bytes` with `trust`, writes its assets under
339/// `assets_root` (`<root>/<app id>/<package hash>/`, once per package) and
340/// records its build (older builds of the app are refused from now on).
341#[cfg(feature = "js")]
342pub fn load_package(
343    trust: &mut nsh_package::TrustStore,
344    bytes: &[u8],
345    assets_root: &std::path::Path,
346) -> Result<LoadedPackage, String> {
347    let package = trust
348        .verify(bytes, BYTECODE_VERSION)
349        .map_err(|e| e.to_string())?;
350    let bundle = Bundle::from_package(&package)?;
351    let dir = assets_root.join(&package.app.id).join(&package.sha256);
352    let done = dir.join(".complete");
353    if !done.exists() {
354        let assets = dir.join("assets");
355        for (path, data) in &package.assets {
356            // Paths were checked (relative, no `..`) when the package was read.
357            let dest = assets.join(path);
358            if let Some(parent) = dest.parent() {
359                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
360            }
361            std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
362        }
363        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
364        std::fs::write(&done, b"").map_err(|e| e.to_string())?;
365    }
366    trust.accept(&package).map_err(|e| e.to_string())?;
367    Ok(LoadedPackage {
368        bundle,
369        assets: dir.join("assets"),
370        app: package.app,
371    })
372}
373
374/// Parses capabilities in their JSON form (`capabilities.json`, the dev
375/// protocol, an embedder's grant).
376pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
377    let value: serde_json::Value =
378        serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
379    Capabilities::from_json(&value)
380}
381
382impl Bundle {
383    /// The declared capabilities from their JSON form, if any.
384    pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
385        self.policy.declared = json.map(parse_capabilities).transpose()?;
386        Ok(self)
387    }
388}
389
390/// Receives mount batches on the engine thread. Implementations forward
391/// them to the UI thread.
392pub trait MountSink: Send + 'static {
393    /// Called once per commit, in order.
394    fn submit(&self, batch: MountBatch);
395
396    /// A fatal app error: the bundle failed to load, or an exception escaped
397    /// a JS callback. Errors are always logged; development hosts also show
398    /// them on screen.
399    fn report_error(&self, _message: &str) {}
400
401    /// JS or a component's task asked for a display frame
402    /// (`requestAnimationFrame`, `ui::ambient::next_frame`): call
403    /// [`EngineControl::frame`] at the next vsync. Requests are not repeated
404    /// until that call.
405    fn request_frame(&self) {}
406
407    /// A development update ([`EngineControl::hot_update`]) could not be
408    /// applied in place: reload the latest full bundle.
409    fn hot_update_failed(&self) {}
410
411    /// The engine laid the app out at `size` ([`EngineControl::resize`]):
412    /// called after the commit of the turn that applied the resize (if it
413    /// changed anything, its batch came before), once per turn, with the
414    /// latest size. A platform that waits for the layout at a new size, to
415    /// show it in the frame the window takes the size, stops waiting here.
416    fn resized(&self, _size: Size) {}
417
418    /// The app imports chunk `id` of a split bundle (`import()`), which its
419    /// [`Bundle`] does not hold: load it and hand it over with
420    /// [`EngineControl::chunk_loaded`] (or [`EngineControl::chunk_failed`]),
421    /// from any thread, and return true. False (the default): this host
422    /// has no chunks to load, and the import fails.
423    fn load_chunk(&self, _id: &str) -> bool {
424        false
425    }
426}
427
428/// Receives what happens to a request started by [`Network::fetch`], in
429/// order, on any thread. After [`FetchTask::cancel`] it may still be called
430/// (the engine then ignores it).
431pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
432
433/// A request in flight, driven from the engine thread.
434pub trait FetchTask: Send {
435    /// The next chunk of a streamed body ([`HttpBody::Stream`]), after
436    /// [`FetchEvent::BodyWanted`].
437    fn send(&mut self, chunk: Vec<u8>);
438    /// A streamed body is complete.
439    fn finish(&mut self);
440    /// Stops (`true`) or resumes (`false`) reading the response body: JS
441    /// does not read what arrived (back pressure). Bytes already on their
442    /// way may still arrive.
443    fn pause(&mut self, paused: bool);
444    /// Aborts the request.
445    fn cancel(self: Box<Self>);
446}
447
448/// The platform's HTTP stack, used by JS `fetch`.
449pub trait Network: Send + Sync + 'static {
450    /// Starts `request`: its response head, then its body in chunks as they
451    /// arrive, are reported to `events`.
452    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
453}
454
455/// Reads the app's bundled files (`asset:/…` URIs): from the app's
456/// resources, or from the dev server during development.
457pub trait Assets: Send + Sync + 'static {
458    /// The bytes of `uri`. Blocking; called on the engine thread.
459    fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
460}
461
462/// Engine settings.
463#[derive(Clone)]
464pub struct EngineConfig {
465    /// The app.
466    pub app: App,
467    /// Initial size of the root view.
468    pub viewport: Size,
469    /// Log per-commit timings (target `nsh::perf`, level info).
470    pub trace: bool,
471    /// The HTTP stack behind `fetch`; without one, requests fail.
472    pub network: Option<Arc<dyn Network>>,
473    /// Source of bundled files such as fonts; without one, they fail to load.
474    pub assets: Option<Arc<dyn Assets>>,
475    /// The surface's initial environment (its `window` is `viewport`).
476    pub environment: Environment,
477    /// Height of the platform's screen header bar, normal and with a large
478    /// title (status bar excluded).
479    pub header_heights: (f32, f32),
480    /// The JS VM's resource limits (a JS app's; Rust code has none).
481    pub limits: Limits,
482    /// The UI sets JS imports (`nsh_ui_mobile::registry()` on mobile, the
483    /// app's own): their Rust components and modules. A Rust app's
484    /// components need no registration.
485    pub ui_sets: Vec<nsh_core::ui::Registry>,
486    /// The tokio runtime the components' async tasks use (timers, IO,
487    /// background work); `None`: one shared by the engines of the process.
488    pub runtime: Option<tokio::runtime::Handle>,
489}
490
491#[cfg(not(target_arch = "wasm32"))]
492/// The runtime of components' tasks when the embedder gives none: a few
493/// threads, made on first use, shared by every engine (like a thread pool,
494/// it holds no engine's state).
495fn shared_runtime() -> tokio::runtime::Handle {
496    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
497    RUNTIME
498        .get_or_init(|| {
499            tokio::runtime::Builder::new_multi_thread()
500                .worker_threads(2)
501                .thread_name("nsh-tasks")
502                .enable_all()
503                .build()
504                .expect("the tasks' runtime starts")
505        })
506        .handle()
507        .clone()
508}
509
510impl std::fmt::Debug for EngineConfig {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        f.debug_struct("EngineConfig")
513            .field("app", &self.app)
514            .field("viewport", &self.viewport)
515            .field("trace", &self.trace)
516            .field("network", &self.network.is_some())
517            .field("assets", &self.assets.is_some())
518            .field("environment", &self.environment)
519            .field("header_heights", &self.header_heights)
520            .field("limits", &self.limits)
521            .field("ui_sets", &self.ui_sets)
522            .finish()
523    }
524}
525
526enum Message {
527    Event(NodeId, EventKind, EventPayload),
528    Scroll(NodeId, f32, f32, u32),
529    Zoom(NodeId, f32),
530    ComponentSize(NodeId, Size),
531    AnimationsFinished(Vec<nsh_animation::Finished>),
532    Resize(Size),
533    /// A component's task was woken: it runs in the loop.
534    Wake,
535    Environment(Environment),
536    RootSize(NodeId, Size, EdgeInsets),
537    ScreenHeader(NodeId, Option<f32>),
538    Frame,
539    States(NodeId, u8),
540    FontsChanged,
541    /// An event of a request (by the hop it is for: events of a hop the
542    /// engine left are dropped).
543    Fetch(RequestId, u64, FetchEvent),
544    Hot(HotUpdate),
545    /// A chunk [`MountSink::load_chunk`] was asked for, or why it could
546    /// not be loaded (its id and the message).
547    Chunk(Result<Chunk, (String, String)>),
548    Perf(Option<Arc<perf::PerfMonitor>>),
549    /// The embedding app's theme.
550    Theme(Option<Box<Theme>>),
551    /// Sent by a dropped [`Engine`] (there is none in WebAssembly).
552    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
553    Shutdown,
554}
555
556/// A development update that replaces the app's changed modules in place,
557/// keeping the JS context, the views and the state of everything else
558/// (made by `nsh_bundler::HotBundle::patch`).
559#[derive(Debug, Clone)]
560pub struct HotUpdate {
561    /// Script name in stack traces, unique per update (e.g. `hot-3.js`).
562    pub name: String,
563    /// The script.
564    pub code: String,
565    /// Its source map (JSON).
566    pub source_map: Option<Arc<str>>,
567}
568
569/// Rounds of "list asks for items -> JS renders them -> layout" folded into
570/// one frame. Bounded so a list that never settles cannot stall the engine;
571/// leftovers continue next frame.
572const MAX_LIST_ROUNDS: usize = 8;
573
574/// A cheap, cloneable handle for sending input to the engine from any thread.
575#[derive(Clone)]
576pub struct EngineControl {
577    tx: Sender<Message>,
578}
579
580impl EngineControl {
581    /// Delivers an input event (and its data) to a node.
582    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
583        let _ = self.tx.send(Message::Event(id, event, payload));
584    }
585
586    /// Reports the content offset of a scroll view or list, and how many
587    /// scrolls the core asked for (`MountItem::ScrollBy` items and
588    /// `Command::ScrollTo` commands for the view) were applied before it.
589    /// Cheap to call on every scroll frame: offsets are coalesced per
590    /// engine frame.
591    pub fn scroll(&self, id: NodeId, x: f32, y: f32, applied: u32) {
592        let _ = self.tx.send(Message::Scroll(id, x, y, applied));
593    }
594
595    /// Reports the zoom scale of a zoomable scroll view (before the offset
596    /// the zoom changed); `onScroll` carries it.
597    pub fn zoom(&self, id: NodeId, scale: f32) {
598        let _ = self.tx.send(Message::Zoom(id, scale));
599    }
600
601    /// A registered native component's own size (points): it is laid out at
602    /// it where its style leaves a dimension open.
603    pub fn set_component_size(&self, id: NodeId, size: Size) {
604        let _ = self.tx.send(Message::ComponentSize(id, size));
605    }
606
607    /// Reports native animations that finished or were interrupted.
608    pub fn animations_finished(&self, finished: Vec<nsh_animation::Finished>) {
609        let _ = self.tx.send(Message::AnimationsFinished(finished));
610    }
611
612    /// Resizes the root view.
613    pub fn resize(&self, size: Size) {
614        let _ = self.tx.send(Message::Resize(size));
615    }
616
617    /// Reports a change of the surface's environment (safe area, keyboard,
618    /// appearance...).
619    pub fn set_environment(&self, environment: Environment) {
620        let _ = self.tx.send(Message::Environment(environment));
621    }
622
623    /// The platform presents root `id` (a modal) at `size`, with `insets`
624    /// of it covered by system UI.
625    pub fn set_root_size(&self, id: NodeId, size: Size, insets: EdgeInsets) {
626        let _ = self.tx.send(Message::RootSize(id, size, insets));
627    }
628
629    /// The platform measured where the content of screen `id` starts below
630    /// its header (`None`: let the core estimate it).
631    pub fn set_screen_header(&self, id: NodeId, height: Option<f32>) {
632        let _ = self.tx.send(Message::ScreenHeader(id, height));
633    }
634
635    /// Applies a development update in place. When it cannot be applied,
636    /// [`MountSink::hot_update_failed`] asks the platform to reload.
637    pub fn hot_update(&self, update: HotUpdate) {
638        let _ = self.tx.send(Message::Hot(update));
639    }
640
641    /// Hands over the chunk [`MountSink::load_chunk`] asked for: the
642    /// dynamic imports waiting for it continue.
643    pub fn chunk_loaded(&self, chunk: Chunk) {
644        let _ = self.tx.send(Message::Chunk(Ok(chunk)));
645    }
646
647    /// Chunk `id` could not be loaded: the dynamic imports waiting for it
648    /// fail with `message` (a later import asks for it again).
649    pub fn chunk_failed(&self, id: String, message: String) {
650        let _ = self.tx.send(Message::Chunk(Err((id, message))));
651    }
652
653    /// A display frame began, after [`MountSink::request_frame`]: runs the
654    /// `requestAnimationFrame` callbacks and the tasks waiting for it.
655    pub fn frame(&self) {
656        let _ = self.tx.send(Message::Frame);
657    }
658
659    /// Reports the interaction states of view `id` that the core asked to
660    /// track ([`nsh_core::MountItem::TrackStates`]; bits of
661    /// [`nsh_core::tailwind::state`]). Class styles that depend on them
662    /// (`active:`, `hover:`, `focus:`) update without JS.
663    pub fn set_states(&self, id: NodeId, states: u8) {
664        let _ = self.tx.send(Message::States(id, states));
665    }
666
667    /// Fonts the platform loads asynchronously became usable (on the web,
668    /// a `FontFace` finished loading): text measured with a fallback font
669    /// is measured again.
670    pub fn fonts_changed(&self) {
671        let _ = self.tx.send(Message::FontsChanged);
672    }
673
674    /// Records the engine's commits into `monitor` from now on (`None`:
675    /// stops). Measuring costs nothing while no monitor is installed.
676    pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
677        let _ = self.tx.send(Message::Perf(monitor));
678    }
679
680    /// Sets the embedding app's theme, which the UI sets' components
681    /// render with instead of the app's own (`None`: the app's again;
682    /// [`Core::set_host_theme`]). Sent from [`Engine::start_with`]'s
683    /// `setup`, it is in the first frame.
684    pub fn set_theme(&self, theme: Option<Theme>) {
685        let _ = self.tx.send(Message::Theme(theme.map(Box::new)));
686    }
687}
688
689#[cfg(not(target_arch = "wasm32"))]
690/// A running engine. Dropping it stops the thread.
691pub struct Engine {
692    control: EngineControl,
693    thread: Option<std::thread::JoinHandle<()>>,
694    /// Interrupts running JS when the engine stops.
695    stop: Arc<std::sync::atomic::AtomicBool>,
696}
697
698#[cfg(not(target_arch = "wasm32"))]
699impl Engine {
700    /// Starts the engine thread. `make_text_engine` runs on that thread.
701    pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
702    where
703        M: TextEngine + 'static,
704        F: FnOnce() -> M + Send + 'static,
705        S: MountSink,
706    {
707        Self::start_with(config, make_text_engine, sink, |_| {})
708    }
709
710    /// [`Engine::start`], with `setup` sending input before the engine
711    /// starts: what it sends (a theme, the environment) is applied before
712    /// the first frame.
713    pub fn start_with<M, F, S>(
714        config: EngineConfig,
715        make_text_engine: F,
716        sink: S,
717        setup: impl FnOnce(&EngineControl),
718    ) -> io::Result<Engine>
719    where
720        M: TextEngine + 'static,
721        F: FnOnce() -> M + Send + 'static,
722        S: MountSink,
723    {
724        let (tx, rx) = crossbeam_channel::unbounded();
725        setup(&EngineControl { tx: tx.clone() });
726        let engine_tx = tx.clone();
727        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
728        let engine_stop = stop.clone();
729        let thread = std::thread::Builder::new()
730            .name("nsh-engine".into())
731            .stack_size(ENGINE_STACK_SIZE)
732            .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
733        Ok(Engine {
734            control: EngineControl { tx },
735            thread: Some(thread),
736            stop,
737        })
738    }
739
740    /// A handle for sending input from other threads.
741    pub fn control(&self) -> EngineControl {
742        self.control.clone()
743    }
744}
745
746#[cfg(not(target_arch = "wasm32"))]
747impl Drop for Engine {
748    fn drop(&mut self) {
749        // Dropped on the platform's main thread: a script still running is
750        // aborted rather than waited for.
751        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
752        let _ = self.control.tx.send(Message::Shutdown);
753        if let Some(thread) = self.thread.take() {
754            let _ = thread.join();
755        }
756    }
757}
758
759#[cfg(not(target_arch = "wasm32"))]
760/// The engine thread turns input into frames: it is as latency-critical as
761/// the UI thread. Without this, Apple platforms may run it on efficiency
762/// cores at low clock speeds.
763fn raise_thread_priority() {
764    #[cfg(target_vendor = "apple")]
765    // SAFETY: changes the QoS class of the calling thread only.
766    unsafe {
767        libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
768    }
769}
770
771#[cfg(not(target_arch = "wasm32"))]
772fn run<M: TextEngine + 'static, S: MountSink>(
773    config: EngineConfig,
774    text_engine: M,
775    sink: S,
776    tx: Sender<Message>,
777    rx: Receiver<Message>,
778    stop: Arc<std::sync::atomic::AtomicBool>,
779) {
780    raise_thread_priority();
781    let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
782        return;
783    };
784    loop {
785        let message = match driver.deadline() {
786            Some(deadline) => match rx.recv_deadline(deadline) {
787                Ok(message) => Some(message),
788                Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
789                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
790            },
791            None => match rx.recv() {
792                Ok(message) => Some(message),
793                Err(_) => return,
794            },
795        };
796        let started = driver.state.perf.is_some().then(Instant::now);
797        if let Some(message) = message {
798            if !driver.handle(message) {
799                return;
800            }
801            // Coalesce everything already queued into this frame.
802            while let Ok(message) = rx.try_recv() {
803                if !driver.handle(message) {
804                    return;
805                }
806            }
807        }
808        driver.turn();
809        driver.state.record_perf(started);
810        if rx.is_empty() {
811            driver.collect_if_idle();
812        }
813    }
814}
815
816/// An engine driven by its host's event loop instead of a thread of its
817/// own: the browser's main thread in WebAssembly, where there are no
818/// threads to block. Input sent through its [`EngineControl`] is handled
819/// at the next [`LocalEngine::pump`].
820pub struct LocalEngine<M: TextEngine + 'static> {
821    driver: Driver<M>,
822    rx: Receiver<Message>,
823    control: EngineControl,
824}
825
826impl<M: TextEngine + 'static> LocalEngine<M> {
827    /// Starts the app (its first frame goes to `sink` before this returns);
828    /// `None` if it could not start (reported to `sink`).
829    pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
830        let (tx, rx) = crossbeam_channel::unbounded();
831        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
832        let control = EngineControl { tx: tx.clone() };
833        let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
834        Some(LocalEngine {
835            driver,
836            rx,
837            control,
838        })
839    }
840
841    /// A handle for sending input.
842    pub fn control(&self) -> EngineControl {
843        self.control.clone()
844    }
845
846    /// Handles the input sent since the last call, runs what is due
847    /// (timers, tasks) and commits. Returns when to call again at the
848    /// latest (sooner if input arrives); `None`: only for input.
849    pub fn pump(&mut self) -> Option<Instant> {
850        // Bounded: messages sent while handling (a task waking another)
851        // are handled in the same call, a loop that never settles is not.
852        for _ in 0..4 {
853            let started = self.driver.state.perf.is_some().then(Instant::now);
854            while let Ok(message) = self.rx.try_recv() {
855                self.driver.handle(message);
856            }
857            self.driver.turn();
858            self.driver.state.record_perf(started);
859            if self.rx.is_empty() {
860                break;
861            }
862        }
863        self.driver.collect_if_idle();
864        self.driver.deadline()
865    }
866}
867
868/// One engine's state and the work of one wake-up, whoever drives it.
869struct Driver<M: TextEngine + 'static> {
870    state: State<Rc<M>>,
871    script: Option<Script>,
872    sink: Rc<dyn MountSink>,
873    assets: Option<Arc<dyn Assets>>,
874    /// A VM stopped for good (out of memory, over a quota) is reported
875    /// once; its views stay as they were and no JS runs any more.
876    stopped: bool,
877    last_gc: Instant,
878}
879
880impl<M: TextEngine + 'static> Driver<M> {
881    /// Sets up the core, starts the app and submits its first frame.
882    fn start(
883        config: EngineConfig,
884        text_engine: M,
885        sink: Rc<dyn MountSink>,
886        tx: Sender<Message>,
887        rx: &Receiver<Message>,
888        stop: Arc<std::sync::atomic::AtomicBool>,
889    ) -> Option<Self> {
890        let text_engine = Rc::new(text_engine);
891        let access = Arc::new(match &config.app {
892            App::Js(bundle) => bundle.policy.access(),
893            // Native code is trusted: it reaches what the platform allows.
894            App::Rust(_) => Policy::default().access(),
895        });
896        let mut core = Core::new(text_engine.clone(), config.viewport);
897        core.set_components(nsh_core::ui::Registry::merged(&config.ui_sets));
898        if let App::Js(_) = &config.app {
899            // Only JS is limited (Rust code is as trusted as the platform).
900            core.set_max_nodes(config.limits.max_nodes);
901        }
902        core.set_access(access.clone());
903        core.set_font_scale(config.environment.font_scale);
904        core.set_class_environment(class_environment(&config.environment));
905        core.set_header_heights(config.header_heights.0, config.header_heights.1);
906        core.set_safe_area(insets(&config.environment));
907        core.set_environment(ui_environment(&config.environment, config.viewport));
908        // WebAssembly has no threads for a runtime: tasks' timers are
909        // `nsh_core::time`'s there, fired by the driver.
910        #[cfg(not(target_arch = "wasm32"))]
911        core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
912        // A Rust app's theme and fonts come with its root (a JS app's from
913        // its bundle).
914        if let App::Rust(root) = &config.app {
915            if let Some(theme) = root.theme_ref() {
916                core.set_theme(theme.clone());
917            }
918            for font in root.fonts() {
919                if let Err(err) = core.register_font(font) {
920                    log::error!("font failed: {err}");
921                    sink.report_error(&format!("font failed: {err}"));
922                }
923            }
924        }
925        // The fonts the UI sets' crates ship, before anything is measured.
926        let fonts = config
927            .ui_sets
928            .iter()
929            .flat_map(nsh_core::ui::Registry::asset_files)
930            .filter(|file| file.kind == nsh_core::ui::AssetKind::Font);
931        for font in fonts {
932            let result = match config.assets.as_deref() {
933                Some(assets) => assets.read(font.uri),
934                None => Err("this host cannot load assets".to_owned()),
935            }
936            .and_then(|data| core.register_font(&data));
937            if let Err(err) = result {
938                log::error!("font failed: {}: {err}", font.uri);
939                sink.report_error(&format!("font failed: {}: {err}", font.uri));
940            }
941        }
942        // A task woken on any thread wakes the loop.
943        let wake = tx.clone();
944        core.set_task_notify(Arc::new(move || {
945            let _ = wake.send(Message::Wake);
946        }));
947        let state = State {
948            core,
949            frame_requested: false,
950            ops: Vec::new(),
951            binds: Vec::new(),
952            events: Vec::new(),
953            trace: config.trace,
954            perf: None,
955            perf_commit: perf::CommitTiming::default(),
956            committed_since_gc: false,
957            hot: Vec::new(),
958            scroll_events: FxHashMap::default(),
959            touch_move: None,
960            resized: None,
961            net: Net {
962                network: config.network.clone(),
963                tx,
964                queue: NetworkQueue::default(),
965                inflight: FxHashMap::default(),
966                access: access.clone(),
967                hops: 0,
968            },
969        };
970
971        let mut environment = config.environment;
972        environment.window = (config.viewport.width, config.viewport.height);
973        let start = Instant::now();
974        let mut driver = Driver {
975            state,
976            script: None,
977            sink: sink.clone(),
978            assets: config.assets.clone(),
979            stopped: false,
980            last_gc: Instant::now(),
981        };
982        let eval_us = match &config.app {
983            App::Js(bundle) => {
984                let (script, eval_us) = Script::start(
985                    bundle,
986                    config.limits,
987                    &config.ui_sets,
988                    &environment,
989                    text_engine,
990                    stop,
991                    sink,
992                )?;
993                driver.script = Some(script);
994                eval_us
995            }
996            App::Rust(root) => {
997                driver.state.core.mount_root(root);
998                0
999            }
1000        };
1001        let Driver {
1002            state,
1003            script,
1004            sink,
1005            assets,
1006            ..
1007        } = &mut driver;
1008        let script = script.as_ref();
1009        // What was sent before the start (`Engine::start_with`) is in the
1010        // first frame.
1011        while let Ok(message) = rx.try_recv() {
1012            if !handle(script, state, message) {
1013                return None;
1014            }
1015        }
1016        state.load_fonts(script, assets.as_deref(), &**sink);
1017        if let Some(batch) = state.commit(script) {
1018            if state.trace {
1019                log::info!(
1020                    target: "nsh::perf",
1021                    "first frame: eval {eval_us}µs, total {}µs",
1022                    start.elapsed().as_micros()
1023                );
1024            }
1025            sink.submit(batch);
1026        }
1027        state.net.pump(script);
1028        state.load_chunks(script, &**sink);
1029        state.request_frame(script, &**sink);
1030        driver.check_stopped();
1031        Some(driver)
1032    }
1033
1034    /// When the next timer, idle collection or throttled scroll event is
1035    /// due.
1036    fn deadline(&self) -> Option<Instant> {
1037        let script = self.script.as_ref();
1038        let gc_deadline = (script.is_some() && self.state.committed_since_gc)
1039            .then(|| self.last_gc + IDLE_GC_INTERVAL);
1040        let task_timer = self.state.core.next_task_timer();
1041        [
1042            script.and_then(Script::next_timer),
1043            gc_deadline,
1044            self.state.next_scroll_event(),
1045            task_timer,
1046        ]
1047        .into_iter()
1048        .flatten()
1049        .min()
1050    }
1051
1052    /// Handles one message; false on shutdown.
1053    fn handle(&mut self, message: Message) -> bool {
1054        handle(self.script.as_ref(), &mut self.state, message)
1055    }
1056
1057    /// Runs what the handled messages and the time made due, and submits
1058    /// the frame.
1059    fn turn(&mut self) {
1060        let Driver {
1061            state,
1062            script,
1063            sink,
1064            assets,
1065            ..
1066        } = self;
1067        let script = script.as_ref();
1068        let turn_start = state.trace.then(Instant::now);
1069        state.dispatch_touch_move(script);
1070        state.dispatch_scroll_events(script);
1071        let hot = std::mem::take(&mut state.hot);
1072        if let Some(script) = script {
1073            for update in hot {
1074                script.hot_update(update, &**sink);
1075            }
1076            script.run_timers(Instant::now());
1077        }
1078        state.core.run_component_tasks();
1079        // What JS timers and Rust component tasks took; a Rust component
1080        // renders in the commit.
1081        let tasks = turn_start.map(|s| s.elapsed());
1082        state.load_fonts(script, assets.as_deref(), &**sink);
1083        if let Some(batch) = state.commit(script) {
1084            sink.submit(batch);
1085            if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1086                log::info!(
1087                    target: "nsh::perf",
1088                    "turn: {}µs (timers and tasks {}µs)",
1089                    start.elapsed().as_micros(),
1090                    tasks.as_micros(),
1091                );
1092            }
1093        }
1094        if let Some(size) = state.resized.take() {
1095            sink.resized(size);
1096        }
1097        state.net.pump(script);
1098        state.load_chunks(script, &**sink);
1099        state.request_frame(script, &**sink);
1100        self.check_stopped();
1101    }
1102
1103    /// Collects cycles when the engine has been idle long enough, so
1104    /// released nodes free their views.
1105    fn collect_if_idle(&mut self) {
1106        if let Some(script) = &self.script
1107            && self.state.committed_since_gc
1108            && self.last_gc.elapsed() >= IDLE_GC_INTERVAL
1109        {
1110            script.collect_garbage();
1111            self.last_gc = Instant::now();
1112            self.state.committed_since_gc = false;
1113            if let Some(batch) = self.state.commit(Some(script)) {
1114                self.sink.submit(batch);
1115            }
1116        }
1117    }
1118
1119    fn check_stopped(&mut self) {
1120        if let Some(script) = &self.script
1121            && !self.stopped
1122            && let Some(reason) = script.fatal()
1123        {
1124            self.stopped = true;
1125            script.report(&*self.sink, "stopped", &reason);
1126        }
1127    }
1128}
1129
1130struct ScrollEvent {
1131    x: f32,
1132    y: f32,
1133    content: Size,
1134    viewport: Size,
1135    /// The zoom scale.
1136    zoom: f32,
1137    throttle: Duration,
1138    last: Option<Instant>,
1139    /// An offset not reported yet.
1140    pending: bool,
1141}
1142
1143struct State<M: TextEngine> {
1144    core: Core<M>,
1145    /// A display frame was requested and has not begun yet.
1146    frame_requested: bool,
1147    ops: Vec<Op>,
1148    /// List render requests not yet sent to JS.
1149    binds: Vec<ListBind>,
1150    /// Events raised by the core (e.g. `onEndReached`, `onLayout`).
1151    events: Vec<(NodeId, EventKind, EventPayload)>,
1152    trace: bool,
1153    /// Where commit timings go ([`EngineControl::set_perf_monitor`]).
1154    perf: Option<Arc<perf::PerfMonitor>>,
1155    /// The core's share of the wake-up being measured (`layout`, `ops`,
1156    /// `items`; `js` is the rest of the wake-up).
1157    perf_commit: perf::CommitTiming,
1158    committed_since_gc: bool,
1159    net: Net,
1160    /// Development updates to apply.
1161    hot: Vec<HotUpdate>,
1162    /// `onScroll` events: the latest offset per scroll view, sent once per
1163    /// frame at most (and not more often than the view's throttle).
1164    scroll_events: FxHashMap<NodeId, ScrollEvent>,
1165    /// Touch moves not delivered yet: those queued in one frame become one.
1166    touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1167    /// The viewport size a resize set this turn ([`MountSink::resized`]).
1168    resized: Option<Size>,
1169}
1170
1171/// Requests between JS and the platform's network stack.
1172struct Net {
1173    network: Option<Arc<dyn Network>>,
1174    tx: Sender<Message>,
1175    queue: NetworkQueue,
1176    inflight: FxHashMap<RequestId, Inflight>,
1177    /// What the app may reach.
1178    access: Arc<nsh_core::access::Access>,
1179    /// Hops started so far (the id of the next).
1180    hops: u64,
1181}
1182
1183/// A request in flight.
1184struct Inflight {
1185    task: Box<dyn FetchTask>,
1186    /// The hop the task is.
1187    hop: u64,
1188    /// Requests whose redirects the engine follows (to check each hop).
1189    followed: Option<access::Followed>,
1190}
1191
1192impl Net {
1193    /// Hands what JS asked of its requests to the network.
1194    fn pump(&mut self, script: Option<&Script>) {
1195        let Some(script) = script else { return };
1196        script.take_network(&mut self.queue);
1197        for (id, op) in std::mem::take(&mut self.queue.ops) {
1198            match op {
1199                FetchOp::Start(request) => self.request(script, id, request),
1200                FetchOp::Send(chunk) => {
1201                    if let Some(i) = self.inflight.get_mut(&id) {
1202                        i.task.send(chunk);
1203                    }
1204                }
1205                FetchOp::Finish => {
1206                    if let Some(i) = self.inflight.get_mut(&id) {
1207                        i.task.finish();
1208                    }
1209                }
1210                FetchOp::Pause(paused) => {
1211                    if let Some(i) = self.inflight.get_mut(&id) {
1212                        i.task.pause(paused);
1213                    }
1214                }
1215                FetchOp::Cancel => {
1216                    if let Some(i) = self.inflight.remove(&id) {
1217                        i.task.cancel();
1218                    }
1219                }
1220            }
1221        }
1222    }
1223
1224    /// Makes request `id`, if the app may.
1225    fn request(&mut self, script: &Script, id: RequestId, request: HttpRequest) {
1226        if self.access.is_unrestricted() {
1227            self.start(id, request, None);
1228        } else if !self.access.allows_http(&request.method, &request.url) {
1229            let refused = access::refused(&request.method, &request.url);
1230            script.fetch_event(id, FetchEvent::Failed(refused));
1231        } else if request.follow_redirects {
1232            let hop = access::hop(&request);
1233            let followed = access::Followed { request, hops: 0 };
1234            self.start(id, hop, Some(followed));
1235        } else {
1236            self.start(id, request, None);
1237        }
1238    }
1239
1240    /// Hands one request (or redirect hop) to the network.
1241    fn start(&mut self, id: RequestId, request: HttpRequest, followed: Option<access::Followed>) {
1242        self.hops += 1;
1243        let hop = self.hops;
1244        let Some(network) = &self.network else {
1245            let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1246            let _ = self.tx.send(Message::Fetch(id, hop, failed));
1247            return;
1248        };
1249        let tx = self.tx.clone();
1250        let events: FetchEvents = Box::new(move |event| {
1251            let _ = tx.send(Message::Fetch(id, hop, event));
1252        });
1253        let task = network.fetch(request, events);
1254        self.inflight.insert(
1255            id,
1256            Inflight {
1257                task,
1258                hop,
1259                followed,
1260            },
1261        );
1262    }
1263
1264    /// An event of hop `hop` of request `id`: what JS is told, if anything
1265    /// (`None` for events of hops left behind, and redirects the engine
1266    /// follows).
1267    fn event(&mut self, id: RequestId, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
1268        if self.network.is_none() {
1269            return Some(event);
1270        }
1271        let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
1272        match event {
1273            FetchEvent::Head(head) => {
1274                let Some(followed) = &mut inflight.followed else {
1275                    return Some(FetchEvent::Head(head));
1276                };
1277                match access::next(&self.access, followed, head) {
1278                    access::Next::Done(head) => Some(FetchEvent::Head(head)),
1279                    access::Next::Fail(message) => {
1280                        if let Some(i) = self.inflight.remove(&id) {
1281                            i.task.cancel();
1282                        }
1283                        Some(FetchEvent::Failed(message))
1284                    }
1285                    access::Next::Hop(request) => {
1286                        let i = self.inflight.remove(&id)?;
1287                        let followed = i.followed;
1288                        i.task.cancel();
1289                        self.start(id, request, followed);
1290                        None
1291                    }
1292                }
1293            }
1294            FetchEvent::End | FetchEvent::Failed(_) => {
1295                self.inflight.remove(&id);
1296                Some(event)
1297            }
1298            event => Some(event),
1299        }
1300    }
1301}
1302
1303impl<M: TextEngine> State<M> {
1304    /// Ends the measured wake-up that began at `started`
1305    /// ([`EngineControl::set_perf_monitor`]).
1306    fn record_perf(&mut self, started: Option<Instant>) {
1307        let (Some(started), Some(monitor)) = (started, &self.perf) else {
1308            return;
1309        };
1310        let busy = started.elapsed();
1311        monitor.record_busy(busy);
1312        let mut commit = std::mem::take(&mut self.perf_commit);
1313        if commit.ops > 0 || commit.items > 0 {
1314            commit.js = busy.saturating_sub(commit.layout);
1315            monitor.record_commit(commit);
1316        }
1317    }
1318
1319    /// Sends the pending touch move.
1320    fn dispatch_touch_move(&mut self, script: Option<&Script>) {
1321        if let Some((id, touch)) = self.touch_move.take()
1322            && let Some(script) = script
1323        {
1324            script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
1325        }
1326    }
1327
1328    /// When a throttled `onScroll` is due.
1329    fn next_scroll_event(&self) -> Option<Instant> {
1330        self.scroll_events
1331            .values()
1332            .filter(|e| e.pending)
1333            .filter_map(|e| e.last.map(|t| t + e.throttle))
1334            .min()
1335    }
1336
1337    /// Sends the `onScroll` events that are due.
1338    fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
1339        if self.scroll_events.is_empty() {
1340            return;
1341        }
1342        let now = Instant::now();
1343        // Views that stopped listening (or are gone).
1344        let core = &self.core;
1345        self.scroll_events
1346            .retain(|&id, _| core.scroll_listener(id).is_some());
1347        for (&id, e) in &mut self.scroll_events {
1348            if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
1349                continue;
1350            }
1351            e.pending = false;
1352            e.last = Some(now);
1353            let n = |v: f32| PayloadValue::Number(v as f64);
1354            let payload = EventPayload::Map(vec![
1355                ("x", n(e.x)),
1356                ("y", n(e.y)),
1357                ("contentWidth", n(e.content.width)),
1358                ("contentHeight", n(e.content.height)),
1359                ("width", n(e.viewport.width)),
1360                ("height", n(e.viewport.height)),
1361                ("zoomScale", n(e.zoom)),
1362            ]);
1363            // A Rust component's scroll view is the component's.
1364            if !self.core.component_event(id, EventKind::Scroll, &payload)
1365                && let Some(script) = script
1366            {
1367                script.dispatch_event(id, EventKind::Scroll, &payload);
1368            }
1369        }
1370    }
1371
1372    /// Asks the platform for the chunks JS imports and does not have.
1373    fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1374        let Some(script) = script else { return };
1375        let mut ids = Vec::new();
1376        script.take_chunk_requests(&mut ids);
1377        for id in ids {
1378            if !sink.load_chunk(&id) {
1379                let message = "this host does not load chunks (the app was built split)".to_owned();
1380                let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
1381            }
1382        }
1383    }
1384
1385    /// Asks the platform for a frame when JS or a component's task waits
1386    /// for one.
1387    fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1388        if !self.frame_requested
1389            && (script.is_some_and(Script::wants_frame) || self.core.wants_frame())
1390        {
1391            self.frame_requested = true;
1392            sink.request_frame();
1393        }
1394    }
1395
1396    /// Registers fonts imported by JS. Blocking: text using them must not be
1397    /// measured with a fallback font first.
1398    fn load_fonts(
1399        &mut self,
1400        script: Option<&Script>,
1401        assets: Option<&dyn Assets>,
1402        sink: &dyn MountSink,
1403    ) {
1404        let Some(script) = script else { return };
1405        let mut fonts = Vec::new();
1406        script.take_fonts(&mut fonts);
1407        for uri in fonts {
1408            let result = match assets {
1409                Some(assets) => assets.read(&uri),
1410                None => Err("this host cannot load assets".to_owned()),
1411            }
1412            .and_then(|data| self.core.register_font(&data));
1413            if let Err(err) = result {
1414                script.report(sink, "font failed", &format!("{uri}: {err}"));
1415            }
1416        }
1417    }
1418
1419    /// Produces one frame: applies JS ops, lays out, and lets lists pull
1420    /// the items they need, merging everything into a single batch.
1421    fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
1422        let start = Instant::now();
1423        let mut merged: Option<MountBatch> = None;
1424        let mut op_count = 0;
1425        let mut js = std::time::Duration::ZERO;
1426        for _ in 0..MAX_LIST_ROUNDS {
1427            // Requests from the previous round (or frame) first.
1428            let js_start = Instant::now();
1429            // Without JS, lists bind nowhere (Rust components' lists bind in
1430            // the core).
1431            let binds = self.binds.drain(..);
1432            if let Some(script) = script {
1433                for bind in binds {
1434                    script.bind_list(bind.list, &bind.binds);
1435                }
1436            } else {
1437                drop(binds);
1438            }
1439            // The core's events (layouts, ends reached, ...) on a Rust
1440            // component's nodes are the component's; the rest are JS's.
1441            for (id, event, payload) in self.events.drain(..) {
1442                if !self.core.component_event(id, event, &payload)
1443                    && let Some(script) = script
1444                {
1445                    script.dispatch_event(id, event, &payload);
1446                }
1447            }
1448            if let Some(script) = script {
1449                script.take_ops(&mut self.ops);
1450            }
1451            js += js_start.elapsed();
1452            op_count += self.ops.len();
1453            // A stop drops the rest of the ops (`drain` clears them).
1454            for op in self.ops.drain(..) {
1455                match self.core.apply(op) {
1456                    Ok(()) => {}
1457                    Err(err) if err.is_fatal() => {
1458                        let Some(script) = script else { break };
1459                        script.stop(match err {
1460                            ApplyError::TooManyNodes(max) => {
1461                                format!("the app created more than {max} nodes and was stopped")
1462                            }
1463                            other => {
1464                                format!("the app sent an invalid op ({other:?}) and was stopped")
1465                            }
1466                        });
1467                        break;
1468                    }
1469                    Err(err) => log::error!("invalid op: {err:?}"),
1470                }
1471            }
1472            if let Some(batch) = self.core.commit() {
1473                match &mut merged {
1474                    Some(m) => extend_frame(&mut m.items, batch.items),
1475                    None => merged = Some(batch),
1476                }
1477            }
1478            self.core.take_list_binds(&mut self.binds);
1479            self.core.take_events(&mut self.events);
1480            if self.binds.is_empty() && self.events.is_empty() {
1481                break;
1482            }
1483        }
1484        self.committed_since_gc |= op_count > 0;
1485        if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
1486            let c = &mut self.perf_commit;
1487            c.layout += start.elapsed().saturating_sub(js);
1488            c.ops += op_count as u32;
1489            c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
1490        }
1491        if self.trace && (op_count > 0 || merged.is_some()) {
1492            log::info!(
1493                target: "nsh::perf",
1494                "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
1495                start.elapsed().as_micros(),
1496                js.as_micros(),
1497                merged.as_ref().map_or(0, |b| b.items.len()),
1498                self.core.node_count(),
1499            );
1500        }
1501        merged
1502    }
1503}
1504
1505fn insets(env: &Environment) -> EdgeInsets {
1506    let a = env.safe_area;
1507    EdgeInsets {
1508        top: a.top,
1509        right: a.right,
1510        bottom: a.bottom,
1511        left: a.left,
1512    }
1513}
1514
1515/// What Rust components read from the environment.
1516fn ui_environment(env: &Environment, window: Size) -> nsh_core::ui::Environment {
1517    nsh_core::ui::Environment {
1518        window,
1519        safe_area: insets(env),
1520        keyboard_height: env.keyboard_height,
1521        keyboard_duration: env.keyboard_duration,
1522        dark: env.color_scheme == ColorScheme::Dark,
1523        font_scale: env.font_scale,
1524        reduce_motion: env.reduce_motion,
1525        screen_reader: env.screen_reader,
1526        rtl: env.rtl,
1527        pixel_ratio: env.pixel_ratio,
1528        os: env.os,
1529        os_version: env.os_version,
1530        idiom: env.idiom,
1531        locale: env.locale,
1532        apple_keyboard: env.apple_keyboard,
1533    }
1534}
1535
1536/// What class variants read from the environment.
1537fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
1538    nsh_core::tailwind::ClassEnvironment {
1539        dark: env.color_scheme == ColorScheme::Dark,
1540        platform: if env.os == Os::Web {
1541            nsh_core::tailwind::Platform::Web
1542        } else if cfg!(target_os = "android") {
1543            nsh_core::tailwind::Platform::Android
1544        } else {
1545            nsh_core::tailwind::Platform::Ios
1546        },
1547        reduce_motion: env.reduce_motion,
1548    }
1549}
1550
1551/// Returns false on shutdown.
1552fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
1553    match message {
1554        Message::Event(id, event, payload) => {
1555            if state.trace {
1556                log::info!(target: "nsh::perf", "event {event:?} on view {id}");
1557            }
1558            // The core tracks input text for layout and to recognize stale
1559            // values (from JS and from Rust components alike).
1560            if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
1561                state.core.input_changed(id, text, *count);
1562            }
1563            // Events on a Rust component's parts are the component's.
1564            if state.core.component_event(id, event, &payload) {
1565                return true;
1566            }
1567            if let EventPayload::Touch(touch) = payload {
1568                if touch.phase == nsh_core::TouchPhase::Move {
1569                    match &mut state.touch_move {
1570                        Some((_, pending)) => pending.merge_move(*touch),
1571                        None => state.touch_move = Some((id, touch)),
1572                    }
1573                    return true;
1574                }
1575                // Moves before a start, end or cancel go first.
1576                state.dispatch_touch_move(script);
1577                if let Some(script) = script {
1578                    script.dispatch_event(id, event, &EventPayload::Touch(touch));
1579                }
1580                return true;
1581            }
1582            let Some(script) = script else { return true };
1583            let start = state.trace.then(Instant::now);
1584            script.dispatch_event(id, event, &payload);
1585            if let Some(start) = start {
1586                // The handler, its microtasks and the decode of what it
1587                // committed.
1588                log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
1589            }
1590        }
1591        Message::Scroll(id, x, y, applied) => {
1592            state.core.set_scroll_offset(id, x, y, applied);
1593            if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
1594                let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
1595                    x,
1596                    y,
1597                    content,
1598                    viewport,
1599                    zoom,
1600                    throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
1601                    last: None,
1602                    pending: true,
1603                });
1604                (event.x, event.y, event.content, event.viewport, event.zoom) =
1605                    (x, y, content, viewport, zoom);
1606                event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
1607                event.pending = true;
1608            }
1609        }
1610        Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
1611        Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
1612        Message::AnimationsFinished(mut finished) => {
1613            // The components' animations end in the core, JS's in JS.
1614            state.core.animations_finished(&mut finished);
1615            if let Some(script) = script {
1616                script.animations_finished(&finished);
1617            }
1618        }
1619        Message::Resize(size) => {
1620            state.core.set_viewport(size);
1621            state.resized = Some(size);
1622        }
1623        Message::Wake => {}
1624        Message::Environment(env) => {
1625            state.core.set_font_scale(env.font_scale);
1626            state.core.set_class_environment(class_environment(&env));
1627            state.core.set_safe_area(insets(&env));
1628            let window = Size::new(env.window.0, env.window.1);
1629            state.core.set_environment(ui_environment(&env, window));
1630            if let Some(script) = script {
1631                script.set_environment(&env);
1632            }
1633        }
1634        Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
1635        Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
1636        Message::Frame => {
1637            state.frame_requested = false;
1638            state.core.run_frame(Instant::now());
1639            if let Some(script) = script {
1640                script.run_frame();
1641            }
1642        }
1643        Message::States(id, states) => state.core.set_states(id, states),
1644        Message::FontsChanged => state.core.fonts_changed(),
1645        Message::Fetch(id, hop, event) => {
1646            if let Some(event) = state.net.event(id, hop, event)
1647                && let Some(script) = script
1648            {
1649                script.fetch_event(id, event);
1650            }
1651        }
1652        Message::Hot(update) => state.hot.push(update),
1653        Message::Chunk(chunk) => {
1654            if let Some(script) = script {
1655                script.chunk(chunk);
1656            }
1657        }
1658        Message::Perf(monitor) => {
1659            state.perf = monitor;
1660            state.perf_commit = perf::CommitTiming::default();
1661        }
1662        Message::Theme(theme) => state.core.set_host_theme(theme.map(|t| *t)),
1663        Message::Shutdown => return false,
1664    }
1665    true
1666}
1667
1668/// Appends a commit's items to the frame's. A scroll view's content size
1669/// that the frame already sets is updated to the later size (unless the
1670/// view scrolls in between): a row relaid over two commits must not send
1671/// the platform a transient size, which clamps the offset before the
1672/// content grows back (a list jumping when a row expands).
1673fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
1674    use nsh_core::MountItem;
1675    let start = frame.len();
1676    frame.extend(items);
1677    for k in start..frame.len() {
1678        let MountItem::ScrollContent { id, size } = frame[k] else {
1679            continue;
1680        };
1681        let earlier = frame[..k].iter().rposition(|m| {
1682            matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
1683        });
1684        if let Some(j) = earlier
1685            && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
1686        {
1687            *s = size;
1688        }
1689    }
1690}
1691
1692#[cfg(test)]
1693mod tests {
1694    use nsh_core::{MountItem, Size};
1695
1696    #[test]
1697    fn a_frame_sends_a_scroll_views_last_content_size() {
1698        let content = |height| MountItem::ScrollContent {
1699            id: 2,
1700            size: Size::new(390.0, height),
1701        };
1702        let heights = |frame: &[MountItem]| -> Vec<f32> {
1703            frame
1704                .iter()
1705                .filter_map(|m| match m {
1706                    MountItem::ScrollContent { size, .. } => Some(size.height),
1707                    _ => None,
1708                })
1709                .collect()
1710        };
1711        let mut frame = vec![content(313.0)];
1712        super::extend_frame(&mut frame, vec![content(544.0)]);
1713        assert_eq!(heights(&frame), [544.0, 544.0]);
1714        // A scroll in between keeps the size it scrolled against.
1715        let mut frame = vec![
1716            content(313.0),
1717            MountItem::ScrollBy {
1718                id: 2,
1719                dx: 0.0,
1720                dy: 10.0,
1721            },
1722        ];
1723        super::extend_frame(&mut frame, vec![content(544.0)]);
1724        assert_eq!(heights(&frame), [313.0, 544.0]);
1725    }
1726}