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